猫鼬聚合未返回预期结果

时间:2018-11-28 07:18:11

标签: node.js mongodb mongoose

我在跟踪mongoose和mongodb文档之后,正在尝试聚合和一些相关方法。但是我有问题。

Follow.aggregate([
            { $match: { user: mongoose.Types.ObjectId(userId) } },
            { $unwind: '$followers' },
            {
                $lookup: {
                    from: 'accounts',
                    localField: 'followers',
                    foreignField: '_id',
                    as: 'followers'
                }
            },
          { $project: { name: 1, photo: 1 } },

        ]).exec((err, followers) => {
            if (err) throw err;
            console.log(followers);
            res.send(followers);
        });

我想获取该用户ID的关注者,并选择关注者名称和照片,但我仅获取匹配文档的对象ID

[ { _id: 5bfe2c529419a560fb3e92eb } ]

预期产量

 [ { _id: 5bfe2c529419a560fb3e92eb , name: 'john doe", photo: 'cat.jpg'} ]

关注模型

const FollowSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'Account',
        required: true,
    },
    following: [{
        type: Schema.Types.ObjectId,
        ref: 'Account',
        required: true,
    }],
    followers: [{
        type: Schema.Types.ObjectId,
        ref: 'Account',
        required: true,
    }],
});

1 个答案:

答案 0 :(得分:0)

$project阶段出错时,您将得到该结果。尝试先将其删除,然后查看输出。在我看来,您似乎应该在这里找到类似的东西:

{ $project: { "followers.name": 1, "followers.photo": 1 } },
相关问题