Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple elements with different value in Mongoose

I have document containing lists. Lets say they are:

[
 {
  _id: 52b37432b2395e1807000008,
  name: ListA,
  order: 1,
  desc: 'More about List A'
 },
 {
  _id: 52b37432b2395e1807000009,
  name: LISTB,
  order: 2,
  desc: 'More about List B'
 },
 {
  _id: 52b37432b2395e180700000e,
  name: LISTC,
  order: 3,
  desc: 'More about List C'
 },
 {
  ..
 } 
]

Now I want to change their order field using a batch update. I have a JSON of updated_stage order

var updated_stage = [{_id: '52b37432b2395e1807000008', order:2},{_id: '52b37432b2395e180700000e', order:1}, {_id: '52b37432b2395e1807000009', order:3}]

Now I need to update LIST Model in Mongoose with the new array that I have. I know that I can update multiple documents with same value using Batch Update

Model.update({ }, { $set: { order: 10 }}, { multi: true }, callback);

But I have to update them by different values. How should I do it? Whats the most efficient way?

like image 467
Devesh Kumar Avatar asked Dec 31 '13 09:12

Devesh Kumar


People also ask

How do you update multiple documents with different values?

You can not update two documents at once with a MongoDB query. You will always have to do that in two queries. You can of course set a value of a field to the same value, or increment with the same number, but you can not do two distinct updates in MongoDB with the same query.

What is Upsert in mongoose?

May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.

How do I update my mongoose?

There are multiple ways to update documents in Mongoose. You can either use the save() , updateOne() , updateMany() , or findOneAndUpdate() method.


2 Answers

The most efficient way I could think of is to run a forEach loop over your updated_satge array. Now take the _id and update order in the existing document in mongodb.

like image 144
Jayram Avatar answered Oct 05 '22 12:10

Jayram


Here my test with collection.forEach then call doc.save:

I use sync.each to know when all documents is save

var mongoose = require('mongoose'), async = require('async');

mongoose.connect('localhost', 'learn-mongoose');

var User = mongoose.model('User', {name: String});

async.series([
    function (done) {
        // remove User collection if exist
        User.remove(done);
    },

    function(done) {
        // re-create a collection with 2 users 'Mr One', 'Mr Two'
        User.create([{name: 'Mr One'}, {name: 'Mr Two'}], done);
    },

    function(done) {
        // upperCase user.name
        User.find(function(err, users) {
            async.each(users, function(user, callback) {
                user.name = user.name.toUpperCase();
                user.save(callback);
            }, done); // done is call when all users are save!!!!
        });
    },
    function(done) {
        // print result
        User.find(function(err, users) {
            console.log(users);
            done();
        });
    },
], function allTaskCompleted() {
    console.log('done');
    mongoose.disconnect();  
});
like image 38
damphat Avatar answered Oct 05 '22 12:10

damphat