Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongodb更新函数仅在包含.then()时起作用_Node.js_Mongodb_Increment - Fatal编程技术网

Node.js Mongodb更新函数仅在包含.then()时起作用

Node.js Mongodb更新函数仅在包含.then()时起作用,node.js,mongodb,increment,Node.js,Mongodb,Increment,我希望每次提出请求时都在mongodb中增加一个字段。我的更新函数只有在函数调用后包含.then()时才起作用,我不明白为什么 代码正在运行,但我有兴趣理解为什么需要包含.then()。适配器函数以任意一种方式调用,但只有在函数调用后包含.then()时,更新才会显示在db中 更新功能: updateRequestCount: (id) => { return Entry.updateOne({id: id }, { '$inc': { requestCount: 1 } });

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

代码正在运行,但我有兴趣理解为什么需要包含.then()。适配器函数以任意一种方式调用,但只有在函数调用后包含.then()时,更新才会显示在db中

更新功能:

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

updateRequestCount(request.query.id)
.then();
不起作用:

updateRequestCount(request.query.id);

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

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

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

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