【问题标题】:Mongoose - Check if `upsert` made a new document or notMongoose - 检查 `upsert` 是否创建了新文档
【发布时间】:2019-07-02 05:33:02
【问题描述】:

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

注意:我使用的是findByIdAndUpdate

【问题讨论】:

  • 这应该可以工作const data = await User.update({ }, { upsert: true }) console.log(data)
  • @AnthonyWinzlet 这将记录文档内容
  • 那你可能在用findOneAndUpdate?
  • @AnthonyWinzlet 我是findByIdAndUpdate,确切地说,不知道返回值会有所不同。编辑了我的问题
  • 有什么理由不使用update 并使用@AnthonyWinzlet 的便捷答案吗?

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

callbackasync await 甚至与 .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如果它被插入。

【讨论】:

  • 哦,你是对的!由于“旧”文档不存在,它只会返回 null 作为文档。谢谢!
  • 可以,但不要使用new: true :-)
  • @Ashh 我们如何知道new: true 或者有没有办法从 num 对象返回中获取更新。
猜你喜欢
  • 2014-12-22
  • 2015-11-23
  • 2016-08-01
  • 2016-11-11
  • 2012-12-06
  • 1970-01-01
  • 2016-04-30
  • 2019-10-05
  • 2015-10-13
相关资源
最近更新 更多