首页 > 解决方案 > 聚合组合两个 ObjectAarray

问题描述

我想将评论的用户与 NodeJS 中的个人资料图片结合起来,以便在出现评论时显示个人资料图片。

我有以下代码:

 Mission.aggregate([
        {
            $match: {
                _id: ({ $in: [mongoose.Types.ObjectId(id)] })
            }
        },
        {
            $limit: 1
        },
        {
            $unwind: {
                "path": "$comments",
                "preserveNullAndEmptyArrays": true
            }
        },
        {
            $lookup: {
                "from": "users",
                "localField": "comments.user",
                "foreignField": "username",
                "as": "user"
            }
        },
        {
            $unwind: {
                "path": "$user",
                "preserveNullAndEmptyArrays": true
            }
        },
        {
            $group: {
                "_id": "$_id",
                "comment": { "$push": "$comments" },
                "user": { "$push": "$user.profilePicture" },
            }
        }
     ], ...)

任务模型如下所示:

creator: {
        type: String,
        required: true
    },
    text: {
        type: String,
        required: true,
        minlength: 4,
        maxlength: 100
    },
comments: [{
        user: {
            type: String,
            required: true
        },
        text: {
            type: String,
            required: true,
            minLength: 2,
            maxLength: 500
        },
        date: {
            date: Date
        }
    }]

用户模型如下所示:

 username: {
            type: String,
            required: true,
            index: { unique: true },
            minlength: 3,
            maxlength: 16
        },
        password: {
            type: String,
            required: true,
            minlength: 60,
            maxlength: 60
        },
        email: {
            type: String,
            required: true,
            validate: {
                validator: function (v) {
                    return /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(v);
                },
                message: '{VALUE} is not a valid email address!'
            },
        },
        profilePicture: {
            type: String
        },
        creationDate: {
            type: Date,
        },
        api: {
            apiKey: {
                type: String
            },
            apiSecret: {
                type: String
            }
        }

问题是:如何在同一个对象中获取评论和 profilePicture?

标签: javascriptnode.jsmongodbmongooseaggregation-framework

解决方案


试着写(愿这对你有用)

     {
        $group: {
            "_id": "$_id",
            "userInfo":{
              $push: {
               "comment": "$comments",
               "user": "$user.profilePicture"
             }
           }
        }
     } 

推荐阅读