首页 > 解决方案 > 无法使用 mongoose 在 mongodb 中增加字段

问题描述

我在 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.jsmongodbexpressmongoosenosql

解决方案


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

试试这个:

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

操场

编辑:

用法:

 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++;
}

推荐阅读