首页 > 解决方案 > 如何使用 Mongoose 将新对象添加到 MongoDB 中特定对象的数组中?

问题描述

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

我想将一个新对象推送到like_count现有帖子文档的数组中,其中postId将与给定值匹配。

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

另外,告诉我我是如何定义Users模型的,还是应该为那些数组对象使用子文档?

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 }
          }
        ]
      }
    ],
})

标签: node.jsmongodbmongoosenosql

解决方案


您可以使用$pushandarrayFilters运算符来实现这一点:

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

推荐阅读