我在跟踪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,
}],
});
答案 0 :(得分:0)
当$project
阶段出错时,您将得到该结果。尝试先将其删除,然后查看输出。在我看来,您似乎应该在这里找到类似的东西:
{ $project: { "followers.name": 1, "followers.photo": 1 } },