MongoDB,猫鼬,更新数组内的对象

时间:2019-02-14 10:02:33

标签: javascript node.js 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的对象的“ trust”值变为“ bad”?

我假设我应该首先找到与端口号“ 116”匹配的集合,然后在“ service”数组中找到“ id”为1的对象。 我该怎么用猫鼬呢?

1 个答案:

答案 0 :(得分:2)

您可以使用$ positional operator更新数组中的值

Relation.findOneAndUpdate(
  { "port": "116", "services.id": "1" },
  { "$set": { "services.$.trust": "bad" }}
)