gpt4 book ai didi

node.js - 使用findOneAndUpdate如何检查文档是否被插入或更新?

转载 作者:可可西里 更新时间:2023-11-01 09:57:02 25 4
gpt4 key购买 nike

Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) {
if(err) console.log(err);

console.log("DOC " + doc)

if(doc.status) {
// FOUND ROOM SATTUS IS TRUE LOGIC
console.log(doc);
// return callback(true)
}
});

以上查询将返回更新或插入的实际文档,但我无法检查到底是哪一个。如果我执行更新而不是 findOneandUpdate 我会返回这个

{
ok: 1,
nModified: 0,
n: 1,
upserted: [ { index: 0, _id: 55df883dd5c3f7cda6f84c78 } ]
}

如何返回文档和写入结果,或者至少返回写入结果中的更新字段。

最佳答案

截至 2019 年 8 月 8 日(Mongoose 版本 5.6.9),要设置的属性是“rawResult”而不是“passRawResult”:

M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) {
if(err) console.log(err);
console.log(d);
});

输出:

{ lastErrorObject:
{ n: 1,
updatedExisting: false,
upserted: 5d4befa6b44b48c3f2d21c75 },
value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' },
ok: 1 }

另请注意,结果作为回调的第二个参数而不是第三个参数返回。可以通过 d.value 检索文档。

关于node.js - 使用findOneAndUpdate如何检查文档是否被插入或更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com