【问题标题】:Mongoose to combine data from 2 schemasMongoose 组合来自 2 个模式的数据
【发布时间】:2019-07-07 03:07:06
【问题描述】:

我在我的猫鼬代码中创建了 2 个不同的架构,如下所示。

    //News Schema
    var newsSchema = mongoose.Schema({
      link: { type: String, index: {unique: true, dropDups: true}, required: 'Kindly enter the link of the news' },
      description: { type: String, required: 'Kindly enter the description of the news' }
    });

    //Comment Schema
    var commentSchema = mongoose.Schema({
      text: { type: String, required: 'Kindly enter the comment text'},
      newsId: { type: mongoose.Schema.Types.ObjectId, ref: "News", required: 'Provide the news ID to which this comment belongs' }
    }, 
    {
      timestamps: true
    });

它有新闻和评论模式。每个新闻项目都有多个 cmets,因此我将新闻 ID 作为评论模式的一部分提供。
当我获取新闻项目列表时,我还希望为每个新闻项目获取前 3 个(或更少,如果可用的 cmets 较少)的 cmets。

是否可以填充或聚合或组合它们?或者有没有更好的处理方法?

【问题讨论】:

  • 是的,你可以用aggregate来做
  • @ŞivāSankĂr 您能否提供一些参考文件或示例来实现它?

标签: mongoose mongoose-schema mongoose-populate


【解决方案1】:

根据创建日期和时间排名前三的评论列表

使用聚合$group 根据newsId 对文档进行分组,然后使用$slice 控制数组中的项目数。

db.comment.aggregate([
    { '$sort': { 'createdAt': 1 } }, //Where timestamps is true
    {
        '$group': {
            '_id': '$newsId',
            'docs': { '$push': '$$ROOT' },
        }
    },
    {
        '$project': {
            'top_three': {
                '$slice': ['$docs', 3]
            }
        }
    }
])

新闻列表,每条新闻有 3 条评论

$lookup$limit 使用聚合

db.news.aggregate([{
    $lookup: {
        from: "comments",
        let: { news: "$_id" },
        pipeline: [
            { $match: { "$expr": { "$eq": ["$newsId", "$$news"] } } },
            { '$sort': { 'createdAt': 1 } },
            { $limit: 3 }
        ],
        as: "comments"
    },
}])

【讨论】:

  • 感谢您的回答。看来你没看懂我的问题。我正在寻找每个新闻项目中最多包含 3 个 cmets 的“新闻”列表。
  • 答案已更新!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2012-11-12
  • 1970-01-01
  • 2012-07-16
  • 2015-11-14
  • 2021-12-17
相关资源
最近更新 更多