node.js - MongoDB 在数据库中查找一个对象并更新其字段

标签 node.js mongodb

问题

我有一个连接到 MongoDB 的 NodeJS 应用程序。我正在追踪某件事发生了多少次。所以,我想要的是:

  1. 检查我构造的对象是否在数据库中(不包括出现次数的字段)
  2. 如果是,则更新其出现次数 +=1
  3. 如果没有,则设置occurrences = 1并插入它

我有一个工作代码:

  const isInDb = await collection.findOne({
     // match all other fields except for the occurrences field
  });
  if(!isInDb) {
    parsedElement.occurrences = 1;
    await collection.insertOne(parsedElement);
  } else {
    await collection.updateOne(isInDb, { $inc: { "occurrences": 1 } });
  }

我的问题

难道就没有更好的办法了吗?理想情况下,它应该类似于 collection.findAndUpdate 或 upsert 或类似的东西。我写的内容是有用的,但对我来说似乎效率低下,因为我首先必须查询数据库进行查找,然后查询它进行更新。

最佳答案

updateOne 采用第三个参数作为选项。设置 upsert: true。

collection.updateOne({ /* match properties */ }, { $inc: { "occurrences": 1 } }, { upsert: true })

关于node.js - MongoDB 在数据库中查找一个对象并更新其字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915919/

相关文章:

javascript - 在循环 + Nodejs 内使用带有 async/await 的循环

json - 使用 Node.js Express 从 mongodb 导出和导入数据

mongodb - mongodb 3上的类型错误

node.js - FindOne 与 MongooseJS 然后提前存储结果?

java - $push 和 $set 在同一个 MongoDB 更新中

javascript - node.js:Mongodb db.collection.find() 在 collection.insert 工作时不工作

javascript - 有没有办法在 Node.js 中使用两个回调函数的值( bool 值)?

node.js - 在 Loopback.js 中,如何在不运行应用程序的情况下运行独立脚本?

javascript - 显示存储在 MongoDb 中的图像

javascript - Express 4 ans Socket.io - 在模块中访问 app.io