【问题标题】:How to add a new Object into an Array of a particular Object in MongoDB using Mongoose?如何使用 Mongoose 将新对象添加到 MongoDB 中特定对象的数组中?
【发布时间】:2020-10-27 19:15:44
【问题描述】:

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

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

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

另外,告诉我我是如何定义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.js mongodb mongoose nosql


    【解决方案1】:

    您可以使用$push 和arrayFilters 运算符来实现:

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

    【讨论】:

    • @Abid - 请使用您自己的增强功能发布单独的答案,而不是尝试通过您的添加来编辑其他人的答案。
    • 你可以使用 async await 来实现你想要的。
    猜你喜欢
    • 2021-09-01
    • 2021-06-04
    • 2021-07-04
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2021-11-06
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多