更新 Mongoose 更新嵌套数组元素

问题描述:

我有以下架构

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

我想为 UserSchema 创建静态方法,以便通过给定的 room _id

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}
    });
}

我不知道如何通过他的元素 room._id 获取聊天元素然后更新它.有什么帮助吗?

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

编辑

我的情况与建议的重复案例相似但不一样,因为那里的人知道所有ids,而我不知道chat._id.

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.

如果有人需要,我会发布解决方案.

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();
};