gpt4 book ai didi

node.js - Mongoose - 检查 `upsert` 是否创建了新文档

转载 作者:可可西里 更新时间:2023-11-01 10:08:47 28 4
gpt4 key购买 nike

有什么方法可以知道 Mongoose 的 upsert 选项是否通过 await 创建了一个新文档?本质上我想做 this除了没有回调。

注意:我正在使用 findByIdAndUpdate

最佳答案

mongoose函数的callbackasync await甚至with .then都没有区别

回调

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 (findByIdAndUpdate) 检查返回的文档是否更新或更新

const num = await User.findOneAndUpdate({ _id: id }, upsertData, { upsert: true })
console.log(num)

所以此处 num 将打印文档(如果它已经存在)或null(如果已插入)。

关于node.js - Mongoose - 检查 `upsert` 是否创建了新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54584544/

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