Lukasz Indyk Lukasz Indyk - 6 months ago 17
Node.js Question

count of updated objects using node mongodb native client

I have the following update MongoDB query, run in Node.js via MongoDB native client. The query works correctly - I see objects being modified in my MongoDB after I run this code:

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


I would like to know what is the number of records that were updated in MongoDB after my query. I have seen that I can do check it by running getLastError in MongoDB, but I am not sure how to do it from Node.js using the native client.

Any hints how to do it? Is there any other way than calling getLastError?

Answer

The second parameter to the update callback is the count of affected docs:

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

Update for the 2.x version of the native driver:

The second parameter to the update callback is now a nested object, where the number of documents updated can be found in result.nModified.

collection.update(
    { _id : request.query.person },
    { $inc: { score : 1 }},
    { safe : true},
    function (err, response) {
        console.log(response.result.nModified);
    }
);
Comments