简体   繁体   中英

.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

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}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM