Godshand
Godshand

Reputation: 631

Find and update many documents listed in an array

I'm trying to update my database by finding all documents that are matched listed in an array, then update the multiple documents that are listed, I was able to update a single document using findOne() but when I use find() to look for all documents that are matched in the array.. it doesn't update. Any solution for this?

Sample documents:

_id:5c5ef16221a4961b68e64d98
serial_code:"one"
status:"available"

_id:5c5ef17541a4961b68e64d98
serial_code:"two"
status:"available"

My Code:

Bloodstock.find({ serial_code : { $in : ['one','two','three'] } }, function(bloodstock) {                                               
    bloodstock.status = 'not available';                            
    bloodstock.save(function(err) {
        if (err) {
            console.log(err); 
        } else {
            console.log('success'); 
        }
    });  
});

Gives me err:

TypeError: bloodstock.save is not a function

Upvotes: 2

Views: 326

Answers (3)

Rajesh Meniya
Rajesh Meniya

Reputation: 813

You can use update method with option multi: true to update multiple document that match your query.

Bloodstock.update(
  { serial_code : { $in : ['one','two','three'] } },
  { $set: { status: 'not available' }}, 
  { multi: true },
  function (err, result){
    console.log(result)
  }
);

You can check more details about options here: https://docs.mongodb.com/manual/reference/method/db.collection.update/

Upvotes: 0

mickl
mickl

Reputation: 49975

Mongoose's callbacks typically take two arguments and first one represents and error, take a look here. Therefore your code could look like below:

Bloodstock.find({ serial_code : { $in : ['one','two','three'] } }, function(error, bloodstockDocs) {                                               
    if(error) return;
    for(let bloodstock of bloodstockDocs) {
        bloodstock.status = 'not available';                            
        bloodstock.save(function(err) {
            if (err) {
                console.log(err); 
            } else {
                console.log('success'); 
            }
        });
    }  
});

EDIT: find returns a collection so you need to use for loop to iterate through those documents.

Upvotes: 1

Ashh
Ashh

Reputation: 46471

Use update query instead

Bloodstock.update(
  { serial_code : { $in : ['one','two','three'] } },
  { $set: { status: 'not available' }}, 
  { multi: true },
  function (err, result){
    console.log(result)
  }
)

Upvotes: 3

Related Questions