聚合组合两个ObjectAarrays

时间:2018-05-23 21:42:31

标签: javascript node.js mongodb mongoose aggregation-framework

我想将评论的用户与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?

1 个答案:

答案 0 :(得分:0)

尝试写(可能这对你有用)

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