更新 Mongoose 更新嵌套数组元素 [英] Updated Mongoose update nested array element

查看:49
本文介绍了更新 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();
};

这篇关于更新 Mongoose 更新嵌套数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆