【问题标题】:Mongo - Update the database while creating a new entry if necessary [duplicate]Mongo - 如有必要,在创建新条目时更新数据库[重复]
【发布时间】:2014-04-24 17:54:39
【问题描述】:

从 NodeJS(最好使用 Mongoose)更新 Mongo DB 中的行的最佳方法是什么,如果行不存在,则创建它。我尝试了多种功能,savefindOneAndUpdateupdate。它们都相互依赖,例如,必须存在该行才能对其进行更新。

我们如何将这些特性组合成一个函数:

If the entry does not exist by 'name', create it, and then...
If the entry does exist, update 'password' with 'data'

假设 mongo 集合可能如下所示:

{
"_id": ObjectId("5357c8e0b12b6c375bb0217b"),
"name": "Kimberly",
"password": "data"
}

我当前的代码中包含大量 if 语句,并且依赖于 err 响应来调用数据库函数。 (例如,在添加用户之前检查用户是否存在)是否有更好的方法来确保在更新或保存某些内容后数据库中没有重复的条目?

非常感谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以将 findAndModify 与 upsert=true 一起使用

    http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-18
      • 2021-03-04
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2021-08-30
      相关资源
      最近更新 更多