尝试使用findByIdAndUpdate更新MongoDB文档:
var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks');
var lm = new landmarkModel();
//adding data to schema here, like: lm.name = req.body.name;
lm.findByIdAndUpdate(req.body._id, lm, function (err, landmark) {
if (err)
console.log(err);
else{
console.log(null, landmark);
}
});
返回错误:Object lm has no method 'findByIdAndUpdate'
我尝试用lm.findByIdAndUpdate
替换landmarkModel.findByIdAndUpdate
值,但这也不起作用。我做错了什么?
答案 0 :(得分:4)
findByIdAndUpdate
是一种静态方法:
var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks');
var lm = req.body;
delete lm._id;
landmarkModel.findByIdAndUpdate(req.body._id, lm, console.log);
请注意,landmarkModel
接受普通js
个对象。
如果您已有mongoose
个对象,则最好使用save
代替:
var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks');
landmarkModel.findById(req.body._id, function (err, lm) {
if (err) return next(err);
//adding data to schema here, like: lm.name = req.body.name;
lm.save(console.log);
});