如何使用Mongoose将新对象添加到MongoDB中特定对象的数组中?

发布时间:2020-07-07 13:50

这是我的模型,并且数据库中已经有一些文档。

我想将新的 Object 推入现有帖子文档的like_count数组中,其中postId将与给定值匹配。

我第一次使用 猫鼬 。我已经搜索过但没有找到这样的用例。无法理解如何编写逻辑。需要帮助。

另外,请问我可以如何定义Users模型,还是应该对那些数组对象使用 Sub-Document

const Users = new mongoose.Schema({
  username: { type: String, unique: true },
    recent_posts: [
      {
        postId: String,
        posted_at_timestamp: Number,
        like_count: [
          {
            count: Number,
            created_at: { type: Date, default: Date.now }
          }
        ],
        comment_count: [
          {
            count: Number,
            created_at: { type: Date, default: Date.now }
          }
        ]
      }
    ],
})
回答1

您可以使用$pusharrayFilters运算符来实现:

await User.updateOne({
  'recent_posts.postId': postId
}, {
  $push: {
    'recent_posts.$[elem].like_count': newLikeCountObject
  }
}, {
  arrayFilters: [{'elem.postId': postId}]
})