1

尝试使用 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但这也不起作用。我究竟做错了什么?

4

1 回答 1

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);
});
于 2013-08-12T16:03:45.853 回答