tonejac tonejac - 1 month ago 9
Node.js Question

Mongoose Stream, how to update each doc?

I want to update n number of docs based on an array of updateIds. I'm using Mongoose Stream .on('data, function() {}). Which is properly finding all the right docs. But now I'm not sure how to update each doc. Can I just write something like doc.update({query}, {key: value}) inside the on.('data', function(doc){}) ?

Wine.find({
'_id': { $in: updateIds}
}).stream()
.on('data', function(doc){
// how do I update a doc property here?
})
.on('error', function(error) {
throw error;
})
.on('end', function() {
// final callback
});

Answer

You can do it this way.

Wine.find({
    '_id': { $in: updateIds}
}).stream()
   .on('data', function(doc){
       doc.set('property_name', "value");
       doc.save(function(err){
   });
})
.on('error', function(error) {
    throw error;
})
.on('end', function() {
    // final callback
});

Or if you want to update the docs with same data, you can do this,

Wine.update({ _id: { $in: updateIds} },
    { property: "value" },
    { multi : true},
    function(err, count){
    });