Rhy*_*rds 6 mongoose mongodb node.js express mongoose-schema
我正在尝试使用Mongoose和MongoDB向父模式添加子文档但是我被抛出以下错误:
TypeError: User is not a constructor
Run Code Online (Sandbox Code Playgroud)
这是基于Mongoose关于子文档的文档,我认为一切都是一样的.我该如何进一步调试?
路由器
// 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)
})
Run Code Online (Sandbox Code Playgroud)
架构
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)
Run Code Online (Sandbox Code Playgroud)
JavaScript对变量名称区分大小写.您有User模型和User具有相同名称的结果.
您的代码将使用以下更改:
User.findById(id , function (err, user) {
/* ^ use small `u` */
if (err) return handleError(err)
/* rest of your code */
Run Code Online (Sandbox Code Playgroud)
还要记住,在代码中你还要声明另一个名为的变量user.您需要将其更改为不同的内容.