【问题标题】:Updated Mongoose update nested array element [duplicate]更新了 Mongoose 更新嵌套数组元素 [重复]
【发布时间】:2018-07-12 05:33:51
【问题描述】:

我有以下架构

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更新chat[i].lastSeen

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 获取聊天元素然后更新它。有什么帮助吗?

编辑

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

【问题讨论】:

  • @JasonCust 我读了这个但做不到。你能给我一个具体案例的代码吗?

标签: javascript node.js mongodb typescript mongoose


【解决方案1】:

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

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

【讨论】:

  • 也适用于模型(例如 Model.update),在这种情况下不需要 .exec
猜你喜欢
  • 2017-01-24
  • 2022-01-22
  • 2020-10-09
  • 2016-10-06
  • 2016-05-03
  • 2021-04-17
  • 1970-01-01
  • 2017-01-13
相关资源
最近更新 更多