Tra*_*der 3 mongoose mongodb node.js
这是我的架构.
Home = new Schema({
name: { type: String, required: true},
description: {type: String},
administrator: {type : mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
users: [{
_id: {type : mongoose.Schema.Types.ObjectId, ref: 'User'},
email: {type: String},
name: { type: String},
status: { type: Number}
}],
rooms: [Room]
});
module.exports = mongoose.model('Home', Home);
Run Code Online (Sandbox Code Playgroud)
如果我想在多个文档中找到特定用户,我可以这样做
Home.find({"users.email":"johnk@gmail.com"},{users:1})
这将返回所有带有users.email = johnk@gmail.com的房屋
但是用户的字段是一个数组.
"users" : [
{
"status" : 0,
"name" : "Yaknow",
"email" : "yaknow@gmai.com",
"_id" : ObjectId("5875a42ea469f40c684de385")
},
{
"status" : 1,
"name" : "johnk",
"email" : "johnk@gmail.com",
"_id" : ObjectId("586e31c6ce07af6f891f80fd")
}
]
Run Code Online (Sandbox Code Playgroud)
(这只是来自一个家庭,如果有很多家庭,会有很多像这样的阵列)所以上面的查询将返回用户有电子邮件进入的每个家庭的每个用户数组.我的问题是,如何更新所有实例JohnK进入JohnKirtster?使用它会将数组名称中的每个用户更新为JohnKirster
Home.update(query,{users.name:"JohnKirster"})
Jyo*_*aja 13
您可以通过设置使用mongodb $位置运算符multi:true
Home.update(
{"users.name": "johnk"}, //query, you can also query for email
{$set: {"users.$.name": "JohnKirster"}},
{"multi": true} //for multiple documents
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10227 次 |
| 最近记录: |