Mongoose组合来自2个模式的数据

问题描述 投票:0回答:1

我在我的猫鼬代码中创建了两个不同的模式。

    //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
    });

它有新闻和评论架构。每个新闻项目都有多个评论,所以我提供新闻ID作为评论模式的一部分。 当我获取新闻项目列表时,我还想要为每个新闻项目提取前3个(或更少,如果可用的评论更少)评论。 是填充还是聚合或它们的组合是否可能?或者有更好的方法来处理它吗?

mongoose mongoose-schema mongoose-populate
1个回答
0
投票

基于创建日期和时间的前三名评论列表

使用聚合$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"
    },
}])
© www.soinside.com 2019 - 2024. All rights reserved.