gpt4 book ai didi

node.js - 使用 Node mongodb native 客户端更新的对象计数

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:24 24 4
gpt4 key购买 nike

我有以下更新 MongoDB 查询,通过 MongoDB native 客户端在 Node.js 中运行。查询工作正常 - 运行此代码后,我看到 MongoDB 中的对象被修改:

collection.update(
{
_id : request.query.person,
},
{
$inc: {
score : 1
}
},
{ safe : true},
this /* "this" is for Step */
);

我想知道查询后 MongoDB 中更新了多少条记录。我已经看到我可以通过在 MongoDB 中运行 getLastError 来检查它,但我不确定如何使用 native 客户端从 Node.js 执行此操作。

有什么提示吗?除了调用getLastError还有其他方法吗?

最佳答案

update 回调的第二个参数是受影响文档的数量:

collection.update(
{ _id : request.query.person },
{ $inc: { score : 1 }},
{ safe : true},
function (err, numAffected) {
...
}
);

更新 native 驱动程序的2.x版本:

update 回调的第二个参数现在是一个嵌套对象,其中更新的文档数量可以在 result.nModified 中找到。但 update 现已弃用,因此 updateOne应该使用它来代替。

collection.updateOne(
{ _id : request.query.person },
{ $inc: { score : 1 }},
{ safe : true},
function (err, response) {
console.log(response.result.nModified);
// Also available at response.modifiedCount for updateOne, but not update
console.log(response.modifiedCount);
}
);

2.x 回调参数的文档可以在here 找到。 .

关于node.js - 使用 Node mongodb native 客户端更新的对象计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com