我正在尝试使用 Mongoose 和 MongoDB 将子文档添加到父架构,但是我被抛出以下错误:
TypeError: User is not a constructor
这是基于 Mongoose 在 subdocuments 上的文档我认为一切都是一样的。我该如何进一步调试?
路由器
// Add a destination to the DB
router.post('/add', function(req, res, next) {
let airport = req.body.destination
let month = req.body.month
let id = (req.user.id)
User.findById(id , function (err, User) {
if (err) return handleError(err)
function addToCart (airport, month, id) {
var user = new User ({
destinations: [(
airport = '',
month = ''
)]
})
dog.destinations[0].airport = airport
dog.destinations[0].month = month
dog.save(callback)
res.status(200).send('added')
}
addToCart()
})
console.log(airport)
})
架构
var destinationSchema = new Schema({
airport: String,
month: String
})
// Define the scheme
var User = new Schema ({
firstName: {
type: String,
index: true
},
lastName: {
type: String,
index: true
},
email: {
type: String,
index: true
},
homeAirport: {
type: String,
index: true
},
destinations: [destinationSchema]
})
User.plugin(passportLocalMongoose)
module.exports = mongoose.model('User', User)
最佳答案
JavaScript 对变量名区分大小写。您有 User
模型和具有相同名称的 User
结果。
您的代码将适用于以下更改:
User.findById(id , function (err, user) {
/* ^ use small `u` */
if (err) return handleError(err)
/* rest of your code */
另外请记住,在您的代码中,您将声明另一个名为 user
的变量。您需要将其更改为不同的内容。
关于node.js - Mongoose 类型错误 : User is not a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40774997/
相关文章:
node.js - Mongoose 在未指定的时间段后停止响应
java - 如何防止连接池在 mongodb 上使用 java 驱动程序关闭?
mongodb - Meteor 1.4.1.1 上副本集的正确 MONGO_URL 设置是什么
javascript - 为已登录的用户手动创建 Passport session
ruby-on-rails - 在 Rails 控制台中列出所有 Mongoid 模型
node.js - Node/Express - 保护客户端/服务器之间通信的好方法
mongodb - 使用键值对将 mongo 数组转换为对象