【问题标题】:Mongodb update function only works when .then() is includedMongodb 更新功能仅在包含 .then() 时才有效
【发布时间】:2019-01-24 21:25:58
【问题描述】:

我希望每次发出请求时都在 mongodb 中增加一个字段。我的更新函数仅在函数调用后包含 .then() 时才有效,我不明白为什么。

代码正在运行,但我有兴趣了解为什么需要包含 .then()。无论哪种方式都调用适配器函数,但仅当函数调用后包含 .then() 时,更新才会出现在 db 中。

更新函数:

updateRequestCount: (id) => {
    return Entry.updateOne({id: id }, { '$inc': { requestCount: 1 } });
}

作品:

updateRequestCount(request.query.id)
.then();

不起作用:

updateRequestCount(request.query.id);

【问题讨论】:

    标签: node.js mongodb increment


    【解决方案1】:

    当您在 Mongoose 上调用 Model.updateOne() 或模型的任何其他 CRUD 方法时,它会返回一个 Query 对象,该对象有一个 then() 方法,该方法将执行查询并返回一个 Promise

    因此,当您调用 updateOne() 时不会立即执行查询,而只会在您对返回的 Query 对象调用 then() 时执行。

    或者,您可以将回调函数传递给updateOne(),在这种情况下,查询会立即执行,您不必调用then()

    updateRequestCount: (id) => {
      return Entry.updateOne({id: id }, { '$inc': { requestCount: 1 } }, err => {
        // ...
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2021-04-07
      • 2020-06-02
      相关资源
      最近更新 更多