Sean McClory
Sean McClory

Reputation: 4283

Mongoose - How to do a single update with multiple update statements

I see in the mongodb docs that it is possible to send multiple update statements in a single update command. How would you do this with Node.js and Mongoose?

db.runCommand({
    update: <collection>,
    updates:
      [
         { q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
         { q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
         { q: <query>, u: <update>, upsert: <boolean>, multi: <boolean> },
         ...
      ],
    ordered: <boolean>,
    writeConcern: { <write concern> }
})

It seems we can access the driver's db object like this.

 YourModel.db.db

Interested to know if there is a more mongoose friendly way to go about it?

Upvotes: 2

Views: 668

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151190

For mongoose directly there is not specifically any implementation of this right now. But as of writing the mongoose API is still built on top of the node native driver, that makes all the same methods accessible from the model by using the .collection accessor.

So the Bulk API methods are then available:

var bulk =  Model.collection.initializeOrderedBulkOp();
var index = 0

// start some loop of statements
{
    bulk.find({ })             // find to match
        .updateOne({});        // update one      

    bulk.find({})
        .update({});           // applies to multi

    bulk.find({})
        .upsert().updateOne(); // marks an "upsert"
}

bulk.execute(function(err,response) {
    // response object has details of operations
});

Additionally there are all the other methods that can be included in a "bulk" batch, such as .insert() and .remove(), so this works a little cleaner than the raw command form. Which is actually what this will break it down to under the hood.

Beware though that the base driver methods do not work in the same way as the mongoose method implementations do though. The big difference is in the connection to the database. The way mongoose connects and how you can call statements outside of a connection callback means that it's own methods "wait" for that connection to be made before trying to do anything.

So you can use it, but you need to be sure that some other "mongoose" method has always fired before this code would be called. Or otherwise place inside a connection callback or whatever method of connection detection and assurance you need.

Upvotes: 2

Related Questions