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.

1
  • @JasonCust I read this and couldn't do it. Can you give a code for my specific case? Commented Feb 1, 2018 at 19:43

1 Answer 1

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();
};
Sign up to request clarification or add additional context in comments.

1 Comment

Also works from the Model (e.g. Model.update), no .exec is need in this case

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.