【问题标题】:Mongoose update multiple subdocuments from multiple documentsMongoose 从多个文档更新多个子文档
【发布时间】:2020-04-20 23:50:20
【问题描述】:

我想使用 mongoose 从多个文档中更新多个子文档。

我当前的代码是:

const ids: any[] = payload.imageIds.map(e => new ObjectId(e));

await this.userModel
  .updateMany({ 'images._id': { $in: ids } }, { $inc: { 'images.$.views': 1 } })
  .exec();

部分架构是:

export const UserSchema = new mongoose.Schema(
{  
    images: [ImageSchema],
}

const ImageSchema = new mongoose.Schema(
{
    views: { type: Number, default: 0 },
},

但此代码仅更新 ids arr 中的最后一个元素。

【问题讨论】:

  • 你能分享收藏吗?
  • 您能否在问题中添加文档以及预期的输出?
  • 请使用该代码 db.demo.updateMany({ 'images._id': { $in: ids } }, { $inc: { 'images.$[].views': 1 } })
  • Mahesh 使用 $[] 将更新来自该用户的所有图像。我只想更新 ids arr 中的图像

标签: mongodb mongoose nestjs


【解决方案1】:

解决了!

对于遇到同样问题的人:

const imageIds: ObjectId[] = payload.imageIds.map(e => new ObjectId(e));
const userIds: ObjectId[] = payload.userIds.map(e => new ObjectId(e));

 await this.userModel
  .updateMany(
    { _id: { $in: userIds } },
    { $inc: { 'images.$[element].views': 1 } },
    {
      arrayFilters: [
        {
          'element._id': { $in: imageIds },
        },
      ],
    },
  )
  .exec();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2016-02-25
    • 2015-12-22
    • 2021-02-21
    相关资源
    最近更新 更多