简体   繁体   English

.save() 多个文档 mongoose

[英].save() multiple document mongoose

im using mongodb and i want to save the change of multiple document at once.我正在使用 mongodb,我想一次保存多个文档的更改。 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没关系,我得到了我想要的,然后我更改了名称,但是之后当我想保存更改时myUsers.save()给我错误, 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:更新文档的最佳有效方法是使用update方法,如下所示:

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

There are multiple options: update() , updateOne() or updateMany() ...有多个选项: update()updateOne()updateMany() ...

If you only want to update one document you can use findByIdAndUpdate() if you know the document _id or updateOne() .如果您只想更新一个文档,您可以使用findByIdAndUpdate()如果您知道文档_idupdateOne()

The query to update could be something like this example .要更新的查询可能类似于此示例 Note that using mongoose is not necessary {multi: true} if you use updateMany() .请注意,如果您使用updateMany() ,则无需使用mongoose {multi: true}

Into JS is exactly the same:进入 JS 是完全一样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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