Mongoose:如何检查文档是否通过model.findOneAndUpdate()修改

在mongoose中,我们可以检查一个更新操作是否用model.update()修改了文档:

 model.update(query, update, function(err, raw){ if (raw.nModified >= 1) console.log('document is modified!') }); 

有没有办法做到这一点与model.findOneAndUpdate()

 model.findOneAndUpdate(query, update, { new: true }, function(err, doc){ if (doc) { // So MongoDB found the document, but is there a way // to know the document was indeed modified? } }); 

您可以将选项{ passRawResult : true }传递给{ passRawResult : true } ,以通知{ passRawResult : true }传递基础mongodb驱动程序的原始结果,本例中为mongodb-native,作为callback的第三个参数。

用于findOneAndUpdate的 mongodb本地文档

 model.findOneAndUpdate(query, update, { new: true, passRawResult : true }, function(err, doc, res){ // res will look like // { value: { _id: 56a9fc80a7f9a4d41c344852, name: 'hugo updated', __v: 0 }, // lastErrorObject: { updatedExisting: true, n: 1 }, // ok: 1 } }); 

如果更新没有成功,由于没有匹配的文件被发现一个null资源将被传递给callback。 如果文档匹配,但是与更新res对象相同的字段值将不会提供足够的信息来确定是否更新了匹配文档的值。