本文介绍了猫鼬更新文档使用findByIdAndUpdate失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用findByIdAndUpdate更新MongoDB文档:
Trying to update MongoDB document using findByIdAndUpdate:
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'
我尝试用landmarkModel.findByIdAndUpdate
换出lm.findByIdAndUpdate
值,但这也不起作用.我在做什么错了?
I have tried swapping out the lm.findByIdAndUpdate
value with landmarkModel.findByIdAndUpdate
but that doesn't work either. What am I doing wrong?
推荐答案
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
对象.
Note that landmarkModel
accepts plain js
objects.
如果您已经有一个mongoose
对象,那么最好改用save
:
If you already have a mongoose
object then it's best to use save
instead:
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);
});
这篇关于猫鼬更新文档使用findByIdAndUpdate失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!