Suisse
Suisse

Reputation: 3613

Update multiple records in a Model with Waterline on Mongodb

Given is an array with book objects, where each status has to be updated:

var books = [ 
              { id: '58b2e58', status: 'pending' },
              { id: '5903703', status: 'pending' } 
                ]

var status = {status: 'accepted'}

I tried this:

Book.update(books, status).exec(function afterwards(err, updatedbooks) {
            if (err) {
                res.json(err)
                }
            console.log("updatedbooks:", updatedbooks);
});

but the 'updatedbooks' log is empty. When checking in mongodb, the books are there, I can find them with Book.find(books);

As here mentioned this here works fine, but I want to have beside the ID's also the status=="pending" in the WHERE criteria.

Upvotes: 2

Views: 1978

Answers (2)

Foramkumar Parekh
Foramkumar Parekh

Reputation: 541

please try this.

var bookId= ['1','3'];
var status = {status: 'accepted'}
Book.update({id:bookId, status: 'pending'}, status).exec(function afterwards(err, updatedbooks) {
        if (err) {
            console.log('error in update\n'+err);
            res.json(err)
            }
        else{
            console.log("updatedbooks:", updatedbooks);
        }
});

This should work. Also, if you are getting an error, it will give you an idea about what error you are getting.

Upvotes: 2

Suisse
Suisse

Reputation: 3613

If someone has the correct answer, don't wait. I found a workaround:

The find() function can take criteria like this:

var bookCriteria = [ 
              { id: '1', status: 'pending' },
              { id: '3', status: 'pending' } 
                ]

But the update() function only works with an array with ids:

var bookCriteria = [ '1','3']

So lets first search for books which fulfill our criterias and then take those books and update them.

      Book.find(bookCriteria).exec(function (err, booksFounded) {
            //booksFounded is an array with book objects, with status = 'pending'
            //but we need an array with booksFounded ids as strings

              var bookIDs = booksFounded.map( book => book.id}); //['1','3']

            //now update:

                Book.update(bookIDs , {status:'accepted'}).exec(function afterwards(err, updatedbooks) {
                if (err) {
                    res.json(err)
                    }
                console.log("updatedbooks:", updatedbooks);
                });

   })

Do you have a better solution? With my solution it needs 2 DB transactions, but it works.

Upvotes: 0

Related Questions