簡體   English   中英

貓鼬聚合未返回預期結果

[英]mongoose aggregation not returning expected result

在嘗試了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的關注者,並選擇關注者名稱和照片,但我僅獲取匹配文檔的objectid

[ { _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,
    }],
});

$project階段錯誤時,您將得到該結果。 嘗試先將其刪除,然后查看輸出。 對我來說,您似乎應該在這里有以下內容:

{ $project: { "followers.name": 1, "followers.photo": 1 } },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM