首页 > 解决方案 > 如何将 1 添加到 MongoDB 中的值?

问题描述

使用时findOneAndUpdate如何将值加一?在这种情况下,我想将 1 添加到 commandsUsed 对象。下面的例子:

await mongo().then(async (mongoose) => {
   try {
      await userSchema.findOneAndUpdate({
         _id: author.id,
      }, {
         _id: author.id,
         commandsUsed: //I want to add 1 to this Object
      }, {
         upsert: true,
  })

标签: javascriptmongodb

解决方案


您可以使用findOne然后添加字段,最后保存它。

const doc = await userSchema.findOne({ _id: author.id })
doc.commandsUsed++
doc.save();

推荐阅读