2

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?

0

2 Answers 2

1

You can use .dot notation to update in nested object

db.collection.update(
  { },
  { "$set": { "lastMsgRead.user3": "anotherstring" } }
)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.