问题描述
我正在尝试使用Mongoose和MongoDB将子文档添加到父架构中,但是我被抛出以下错误:
I'm trying to add a subdocument to a parent schema with Mongoose and MongoDB however I'm being thrown the following error:
TypeError: User is not a constructor
这基于Monaose在子文档上的文档,我认为所有内容都是相同的.我该如何进一步调试呢?
This is based off Mongoose's documentation on subdocuments and I think everything is the same. How can I debug this further?
路由器
// 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
结果具有相同的名称.
JavaScript is case sensitive about the variable names. You have User
model and the User
result with the same name.
您的代码将进行以下更改:
Your code will work with the following change :
User.findById(id , function (err, user) {
/* ^ use small `u` */
if (err) return handleError(err)
/* rest of your code */
还请记住,在代码中进一步声明了另一个名为user
的变量.您需要将其更改为其他内容.
Also keep in mind that further in your code you are declaring another variable named user
. You will need to change that to something different.
这篇关于猫鼬TypeError:用户不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!