首页 > 解决方案 > 带有 $in 和 arrayFilters 的 mongodb updateMany

问题描述

我有以下集合结构:

{
   _id: userId,
   posts: [{ _id: postId, views: 0 }]
}

我的输入如下:

  1. 带有用户 ID 的数组
  2. 带有帖子 ID 的数组

有了这些信息,我想views为每个匹配的用户/帖子增加,我试过这样:

await Post.updateMany(
    {
      _id: {
        $in: userIds
      }
    },
    {
      $inc: {
        "posts.$[elem].views": 1
      }
    },
    {
      arrayFilters: [
        {
          "elem._id": {
            $in: postIds
          }
        }
      ],
      upsert: true
    }
  );

但我得到了错误:

更新中未使用标识符“elem”的数组过滤器 { $setOnInsert: { __v: 0 } }

我还确保 ID 是 ObjectId 而不是字符串。

那么我在这里做错了什么?

标签: mongodb

解决方案


那么该查询工作正常,我只是忘了将属性添加views到我的猫鼬模型中

添加views到我的模型后,它起作用了

const postSchema = new mongoose.Schema({
  _id: {
    type: mongoose.Types.ObjectId
  },
  posts: [
    {
      _id: {
        type: mongoose.Types.ObjectId
      },
      userid: {
        type: mongoose.Types.ObjectId
      },
      images: {
        type: Object
      },
      category: {
        type: String
      },
      description: {
        type: String
      },
      hashtags: {
        type: Array
      },
      comments: {
        type: Array
      },
      likesUser: {
        type: Array
      },
      time: {
        type: Number
      },
      loading: {
        type: Boolean,
        default: true
      },
      views: {
        type: Number
      }
    }
  ]
});

推荐阅读