Rawand122
Rawand122

Reputation: 375

.save() multiple document mongoose

im using mongodb and i want to save the change of multiple document at once. for example its my code..

const userSchema = new Schema({
 name : String,
 age : Number,
 online : true
})

then for example i want to change the name of two users at once.. i use this method to get users

const myUsers = Users.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
    ]}
}

and its OK i get what i want, then i change names but after that when i want to save changes myUsers.save() gives me error, myUsers.save() is not a function

Upvotes: 0

Views: 601

Answers (1)

J.F.
J.F.

Reputation: 15235

You are in a wrong way. The best an efficient way to update a document is using the update method, like this:

var update = await model.update(...)

There are multiple options: update(), updateOne() or updateMany()...

If you only want to update one document you can use findByIdAndUpdate() if you know the document _id or updateOne().

The query to update could be something like this example. Note that using mongoose is not necessary {multi: true} if you use updateMany().

Into JS is exactly the same:

var update = await model.update({
  "_id": {"$in": yourArrayID}
},
{
  "$set": {"name": yourNewName}
});

Upvotes: 2

Related Questions