MongoDB,mongoose,更新数组内的对象
我有以下MongoDB模型:
const Relation = mongoose.model('Relation',{
name :{
type: String,
},
port:{
type: Number,
},
services: { type : Array , "default" : [] }
});
每个端口都是每个文档的唯一编号。集合可以具有以下值:
{
"port":"116", //unique number
"name":"xzy",
services: [
{"id":'1', "trust":"good"},
{"id":'2', "trust":"bad"},
]
}
例如,如何使“id”= 1的对象的“信任”值“坏”。
我假设我应该首先找到与端口号“116”匹配的集合,然后在Services数组中找到“id”为1的对象。我怎么能在mongoose中做到这一点?
回答如下:您可以使用$
positional operator更新数组中的值
Relation.findOneAndUpdate(
{ "port": "116", "services.id": "1" },
{ "$set": { "services.$.trust": "bad" }}
)