1

I have a User schema with a message field which looks like this:

messages: [{
      receiver: {
        type : Schema.Types.ObjectId,
        ref: 'User'
      },
      history: [{
        user: {
          type : Schema.Types.ObjectId,
          ref: 'User'
        },
        message: {
          type: String
        },
        date: {
          type: Date,
          default: Date.now
        }
      }]
    }]

I'm adding user in message array this way:

await User.update({_id: userID }, {$push: {"messages": {"$each" : [{user: friendID}]}}})

How could I add an object inside history array?

Dennis Braun
  • 259
  • 4
  • 15

1 Answers1

1

You will need to use the positional operator (<array>.$) to match the message you want to update and then $push to the history array within that message.

Note that as explained in the documentation:

The positional $ operator acts as a placeholder for the first element that matches the query document.

Therefore it might be useful to have an _id or some unique identifier for each message in your array. I didn't see something like that in your schema, though. If you use user, then it will match the first message with that user.

You code would therefore be something like:

User.update({ 
  _id: userId,
  "messages.<uniqueIdKey>": <uniqueIdValue>, 
}, 
{
  $push: {
    "messages.$.history": <objectToPush>
  },
});
Juan Carlos Farah
  • 3,829
  • 30
  • 42
  • 2
    I'm using receiver id as a unique key. So this worked fine: `await User.update({_id: userID, "messages.receiver": friendID,},{$push: {"messages.$.history": {user: friendID, message: message}},});` – Dennis Braun Nov 02 '17 at 19:16