【问题标题】:Unable to increment field in mongodb using mongoose无法使用 mongoose 在 mongodb 中增加字段
【发布时间】:2021-08-29 17:39:41
【问题描述】:

我在 mongodb 中有一个文档。此函数中的文档能够找到该文档并将其返回,但我无法终生使用此函数将计数字段更新为 1。如果有帮助,mongodb 中的当前文档是:

{
  _id: 60c5e4c3fba7edd232cf57e7,
  counterName: 'give_me_the_count',
  count: 1,
  updatedAt: 2021-06-13T11:47:02.575Z
}

代码将原始文档返回给 updatedCounter。但 updatedCounter.count 未定义。

  async function updateAndReturnNewCount() {
  let doc = await Counter.findOne({ counterName : "give_me_the_count" })
  var count = doc.count
  let updatedCounter = await Counter.findOneAndUpdate({ counterName : "give_me_the_count" },
                           { $inc: {"count" : 1 }},
                           { new: true,
                            useFindAndModify: false },
                            function(err, doc) {
                              if (err) { console.log(err)}
                              else {console.log("success")}
                            }
                           );
  console.log("updateAndReturnNewCount fired")
  return updatedCounter.count
}

【问题讨论】:

    标签: node.js mongodb express mongoose nosql


    【解决方案1】:

    您的查询对于您想要执行的操作不正确。

    试试这个:

    await Counter.aggregate([
      {
        $match: {
          counterName : "give_me_the_count"
        }
      },
      {
        $set: {
          "count": {
            $add: [ "$count", 1 ] // Increment $count by one
          }
        }
      }
    ])
    

    Playground

    编辑:

    用法:

     async function updateAndReturnNewCount() {
      let doc = await Counter.findOne({ counterName : "give_me_the_count" })
      var count = doc.count
      let updatedCounter = await Counter.aggregate([
      {
        $match: {
          counterName : "give_me_the_count"
        }
      },
      {
        $set: {
          "count": {
            $add: [ "$count", 1 ] // Increment $count by one
          }
        }
      }
    ])
      console.log("updateAndReturnNewCount fired");
      console.log(updatedCounter);
      return count++;
    }
    

    【讨论】:

    • @Marko 我更新了我的分析器。向您展示了使用情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2018-06-14
    • 2020-08-15
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多