Javascript Mongoose:向嵌套对象添加属性
我目前使用的是AngularJS,后端使用的是NodeJS和Express。我使用Mongoose访问数据库。我正试图弄清楚如何向嵌套对象添加属性,但我一辈子都找不到如何在web上的任何地方这样做 我的模式如下所示:Javascript Mongoose:向嵌套对象添加属性,javascript,node.js,mongoose,mongoose-schema,Javascript,Node.js,Mongoose,Mongoose Schema,我目前使用的是AngularJS,后端使用的是NodeJS和Express。我使用Mongoose访问数据库。我正试图弄清楚如何向嵌套对象添加属性,但我一辈子都找不到如何在web上的任何地方这样做 我的模式如下所示: { id: { type: String }, involved: { type: String }, lastMsgRead: Object } lastMsgRead的外观如下所示: { user1: "somestringblahblah",
{
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"
}
}
编辑:
添加属性后,我将如何在将来更新它?在mongoose 5.1.0及更高版本中,您可以使用。 您可以在模式中定义它,如下所示:
{
id: {
type: String
},
involved: {
type: String
},
lastMsgRead: {
type: Map,
of: String
}
}
然后,您可以通过.set(键,值)
并通过.get(key)
可以使用.dot符号在嵌套对象中进行更新
db.collection.update(
{ },
{ "$set": { "lastMsgRead.user3": "anotherstring" } }
)
myDoc.lastMsgRead.get(key)
db.collection.update(
{ },
{ "$set": { "lastMsgRead.user3": "anotherstring" } }
)