MusicDev
MusicDev

Reputation: 94

Mongoose: Adding Attributes to Nested Objects

I'm currently using AngularJS, and the backend is using NodeJS and Express. I use Mongoose to access the database. I'm trying to figure how to add attributes to nested objects and I can't for the life of me find out how to do it anywhere on the web.

My Schema looks like this:

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

}

lastMsgRead will look something like this:

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

and so on. My question is, how would I update lastMsgRead with Mongoose to add another attribute to it, such as adding user3 so it now looks like:

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

The entire document would like this after the update:

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

}

Edit: After I add the attribute, how would I then update it in the future?

Upvotes: 2

Views: 423

Answers (2)

Ashh
Ashh

Reputation: 46451

You can use .dot notation to update in nested object

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

Upvotes: 1

k0hamed
k0hamed

Reputation: 502

in mongoose 5.1.0 and up you can approach this with the MongooseMap. You can define it in the schema as followed:

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

you can then add a new value by .set(key, value)

myDoc.lastMsgRead.set(key, value)

and get a value by .get(key)

myDoc.lastMsgRead.get(key)

Upvotes: 0

Related Questions