Node.js Mongoose-检查'upsert'是否创建了新文档
有没有办法知道Mongoose的Node.js Mongoose-检查'upsert'是否创建了新文档,node.js,mongodb,mongoose,mongodb-query,Node.js,Mongodb,Mongoose,Mongodb Query,有没有办法知道Mongoose的upsert选项是否通过wait创建了新文档?基本上,我想做的只是没有回调 注意:我使用的是findbyiandupdate在回调、异步等待,甚至在with中都没有区别 回调 User.update({ _id: usr._id }, upsertData, { upsert: true }, function(err, num) { console.log(err) console.log(num) } 异步等待 try { const num =
upsert
选项是否通过wait创建了新文档?基本上,我想做的只是没有回调
注意:我使用的是
findbyiandupdate
在回调
、异步等待
,甚至在with中都没有区别
回调
User.update({ _id: usr._id }, upsertData, { upsert: true }, function(err, num) {
console.log(err)
console.log(num)
}
异步等待
try {
const num = await User.update({ _id: usr._id }, upsertData, { upsert: true })
console.log(num)
} catch (err) {
console.log(err)
}
因此,基本上上述两个函数将记录相同的内容
现在,您需要使用findOneAndUpdate
(findbyiandupdate)检查返回的文档是否已更新或更新
因此,此处num
将打印文档(如果文档已存在)或null(如果已插入)。这应该可以const data=wait User.update({},{upsert:true})console.log(data)
@AnthonyWinzlet,它将记录文档内容您可能正在使用的findOneAndUpdate
?@AnthonyWinzlet我是,findbyiandupdate
,确切地说,我不知道返回值会有所不同。编辑了我的问题有没有理由不使用更新并使用@AnthonyWinzlet的方便答案?哦,你说得对!由于“旧”文档不存在,它只会返回null
作为文档。谢谢是,但不要使用new:true
:-)
const num = await User.findOneAndUpdate({ _id: id }, upsertData, { upsert: true })
console.log(num)