我要的是:findOneAndUpdate插入后返回null?
- 回报
1
如果插入成功,即使该文件不存在之前。 - 回报
1
如果更新成功
但我似乎不能findOneAndUpdate
这仅当文档存在并成功更新返回一个结果来实现这一目标。
我的查询:
User.findOneAndUpdate(
{ email: email },
{ $set: { verified: 1 } },
{ upsert: true }
).exec(callback);
我要的是:findOneAndUpdate插入后返回null?
1
如果插入成功,即使该文件不存在之前。1
如果更新成功但我似乎不能findOneAndUpdate
这仅当文档存在并成功更新返回一个结果来实现这一目标。
我的查询:
User.findOneAndUpdate(
{ email: email },
{ $set: { verified: 1 } },
{ upsert: true }
).exec(callback);
假设你想要得到的结果是更新后的文档,则需要修改您的查询,看起来像这样:
User.findOneAndUpdate(
{ email: email },
{ $set: { verified: 1 } },
{ upsert: true, returnNewDocument: true }
).exec(callback);
的returnNewDocument
属性将回调返回更新的文件,而不是原件。对于不存在的文档上的upsert,它将返回新文档而不是空集。
你可以访问本地驱动程序来调用底层集合的updateOne()
或updateMany()
方法,它将从蒙戈在updateWriteOpCallback
回调返回完整的响应,你可以使用一个updateWriteOpResult
对象。例如
User.collection.updateOne(
{ "email": email },
{ "$set": { "verified": 1 } },
{ "upsert": true },
function(err, result) {
// The number of documents that matched the filter.
console.log(result.matchedCount);
// The number of documents that were modified.
console.log(result.modifiedCount);
// The number of documents upserted.
console.log(result.upsertedCount);
// The total count of documents scanned.
console.log(result.result.n);
// The total count of documents modified.
console.log(result.result.nModified);
}
);
在这种情况下,你最有可能需要检查result.result.nModified
和result.upsertedCount
性质作出上述呼吁。
查看[**'WriteResult' **](https://docs.mongodb.com/manual/reference/method/WriteResult/)文档。 – chridam