1

I have the following Schema

UserSchema: Schema = new Schema({
  username: String,
  password: String,
  chat: [{
    lastSeen: { type: Date, default: Date.now },
    room: {
        type: Schema.Types.ObjectId, ref: 'ChatRoom'
    }
  }],
});

I wanna make static method to the UserSchema, so that updates chat[i].lastSeen by given room _id

UserSchema.statics.lastSeen = 
function lastSeen(username: string, roomId: number, date: Date) {
   this.update({
    username: username,
    chat: {
        $elemMatch: {
            'room._id': roomId
        }
    }},
    {
        $set: { 'chat.$[???].lastSeen': date}
    });
}

I can't find out how to get the chat element by his element room._id and then update it. Any help?

EDIT

My case is similar but not the same as suggested duplicate, because the guy there knows all ids, where I don't know chat._id.

Petar Dimov
  • 301
  • 2
  • 11

1 Answers1

12

I'm posting the solution in case someone needs it.

UserSchema.statics.lastSeen = 
function lastSeen(username: string, roomId: number, date: Date) {
    this.update({
      username: username,
      'chat.room': roomId
    }, { $set: { 'chat.$.lastSeen': date }})
    .exec();
};
Petar Dimov
  • 301
  • 2
  • 11