Mongoose findByIdAndUpdate()查找/返回对象,但不更新

我正在尝试使用此代码查找和更新:

exports.updatePlot = async (req, res) => { let modifications = {}; modifications.name = req.body.name; modifications.grower = req.body.props.grower; modifications.variety = req.body.props.variety; modifications.planted = req.body.props.planted; const id = req.body.props.id; try { const updatedPlot = await Plot.findByIdAndUpdate( id, { $set: { modifications } }, { new: true } ); res.json({ updatedPlot }); } catch (e) { return res.status(422).send({ error: { message: 'e', resend: true } }); } }; 

我可以看到,我的请求正文包含数据,我也可以看到,Mongoose正在查找对象,但没有更新它,因为这是它logging的更新情节:

 {"_id":"id string here","name":"old name",...all other properties...} 

我想我的请求是畸形的? 任何人看到我的错误?

Schema看起来像这样:

 const plotSchema = new Schema( { name: String, ...other properties... }, { bufferCommands: false } ); const ModelClass = mongoose.model('plot', plotSchema); 

       

网上收集的解决方案 "Mongoose findByIdAndUpdate()查找/返回对象,但不更新"

您正在将$set对象$set为:

 $set: { modifications: { name: 'xxx', grower: 'xxx', variety: 'xxx' } } 

但是,你想要的是:

 $set: { name: 'xxx', grower: 'xxx', variety: 'xxx' } 

尝试删除查询中modifications的花括号,如下所示:

 const updatedPlot = await Plot.findByIdAndUpdate( id, { $set: modifications }, { new: true } ); 

我认为问题是在请求中,试试这个:

 const updatedPlot = await Plot.findOneAndUpdate( {_id: id}, modifications }, { new: true } );