manjesha
manjesha

Reputation: 59

How can I update 2 or more unique documents in mongoose db

I have 3 unique documents in mydb, I want to update each document using there unique keys that are generated randomly.

I tried updateMany() and update({multi:true}). Using upadteMany() we can update the document that matches the query. Is there any way that I can solve this problem?

Thanks in advance.

If I have the following documents:

doc1 : {
  _id: 1,
  name: 'John Smith',
  age: 20
}

doc2 : {
  _id: 2,
  name: 'Jane Smith',
  age: 22
}

I want the client to be able to pass me both docs in the same request for update. In this case maybe add an address to both docs.

Is there a way the I can send one update statement to mongo such that it updates both of the documents with the name values?

the answer you provided is good. but i modified that code and it looks like

      _id: { $in: [req.params.noteId,req.params.noteId,req.params.noteId]}
   }
   Note.updateMany(query,
       {$set:{
           lname: req.body.lname || "Untitled Note",
           age: req.body.age
       }}
, { new: true }
   )

this code is not working

Upvotes: 1

Views: 81

Answers (1)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

From the below code you can solve your problem . //consider the following object to update

doc1 : {
  _id: 1,
  name: 'John Smith',
  age: 20
}

doc2 : {
  _id: 2,
  name: 'Jane Smith',
  age: 22
}

The below code will change the name of both the docs to manjesha

var criteria =  {
        _id : { $in : [ "1"  , "2"] }
}
userModel.update(criteria  , { name: "manjesha" }, { multi: true },function(err , found){
        if(err){
            res.send(err);
        }else{
            res.send(found);
        }
});
// $in -The $in operator selects the documents where the value of a field equals any value in the specified array.

This will work perfect on your problem .

Upvotes: 1

Related Questions