最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

MongoDB,mongoose,更新数组内的对象

运维笔记admin14浏览0评论

MongoDB,mongoose,更新数组内的对象

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" }}
)
发布评论

评论列表(0)

  1. 暂无评论