【问题标题】:Mongoose: Adding Attributes to Nested ObjectsMongoose:向嵌套对象添加属性
【发布时间】:2018-12-22 23:57:11
【问题描述】:

我目前使用的是 AngularJS,后端使用的是 NodeJS 和 Express。我使用 Mongoose 访问数据库。我试图弄清楚如何为嵌套对象添加属性,但我一生都无法在网络上的任何地方找到如何做到这一点。

我的架构如下所示:

{
id: {
    type: String
},
involved: {
    type: String
},
lastMsgRead: Object

}

lastMsgRead 看起来像这样:

{
    user1: "somestringblahblah",
    user2: "someotherstring",
}

等等。 我的问题是,我将如何使用 Mongoose 更新 lastMsgRead 以向其添加另一个属性,例如添加 user3 所以它现在看起来像:

{
    user1: "somestringblahblah",
    user2: "someotherstring",
    user3: "anotherstring"
}

更新后整个文档会这样:

{
    id: "string",
    involved: "string",
    lastMsgRead: {
        user1: "somestringblahblah",
        user2: "someotherstring",
        user3: "anotherstring"
    }

}

编辑: 添加属性后,我将如何更新它?

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema


    【解决方案1】:

    您可以使用 .dot 表示法在嵌套对象中进行更新

    db.collection.update(
      { },
      { "$set": { "lastMsgRead.user3": "anotherstring" } }
    )
    

    【讨论】:

      【解决方案2】:

      在 mongoose 5.1.0 及更高版本中,您可以使用 MongooseMap 来解决此问题。 您可以在架构中定义它,如下所示:

      {
        id: {
          type: String
        },
        involved: {
          type: String
        },
        lastMsgRead: {
           type: Map,
           of: String
        }
      }
      

      然后您可以通过.set(key, value) 添加一个新值

      myDoc.lastMsgRead.set(key, value)
      

      并通过.get(key)获取值

      myDoc.lastMsgRead.get(key)
      

      【讨论】:

        猜你喜欢
        • 2013-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        相关资源
        最近更新 更多