如何在Mongoose中进行聚合+填充

我感谢一些帮助。 我正在用express和mongodb(v3.4.4),使用mongoose(v4.10.5)做api rest。 我需要做一个聚合操作,但我不处理它。 我给你看一些代码。 模型(它有更多的属性,但我已经离开它简单):

const CategoryModel = mongoose.model('Category', new Schema({ slug: { type: String, unique: true, lowercase: true, index: true }, description: String })); const MyModel = mongoose.model('MyModel', new Schema({ category: { type: Schema.Types.ObjectId, ref: 'Category' }, other: [{ type: Schema.Types.ObjectId, ref: 'Other' }], times_count: { type: Number, default: 0 } })); 

重要的是,我有兴趣填充MyModelcategory字段,而不是other字段。

假设CategoryMyModel具有一定的logging格式。 请求:

 MyModel.aggregate([ { $group : { _id : '$_id', times: { $sum: '$times_count' } } }, { $limit: 5 } ]).limit(5).exec().then((data) => { console.log(data); }).catch((err) => { console.error(err); }); 

data是正确的,有5条logging,但不包括category 。 现在,我试着:

 MyModel.aggregate([ { $group : { _id : '$_id', times: { $sum: '$times_count' } } }, { $limit: 5 }, { $lookup: { from: 'Category', // I tried with 'Categories' and 'categories' localField: 'category', foreignField: '_id', as: 'category' } }, { $unwind: '$category' } ]).limit(5).exec().then((data) => { console.log(data); }).catch((err) => { console.error(err); }); 

现在data是空的。 我设置了mongoose.set('debug', true); 和他们看起来正确的操作,包括上次操作aggregate ,但数据是空的…

我不知道我是否解释得好。 显然有一些我不完全理解的东西。 提前致谢。

我在objs中得到所需的logging,问题是我只带有_id和times属性,而且我需要填充类别。

这是正确的,因为你没有明确地join舞台join其他collections。

我已经尝试添加$项目到$组后的聚合,但没有。

简而言之, $项目是使用一个集合来包含和排除新字段,而不是join。

您正在寻找$查找这是为了join一个集合与另一个。 当您join一个新的集合时,每个文档将有一个新的数组字段,其中包含另一个集合中的“已join”文档。

在你的情况下,你的新数组字段将有另一个集合中的一个文档,所以你可能也想$放松 。

 MyModel.aggregate([ { $group : { _id : '$_id', times: { $sum: '$times_count' }, category: { $first: '$category' } } }, /* { $limit: 5 }, */ { $lookup: { from: 'Categories', localField: 'category', foreignField: '_id', as: 'category' } }, { $unwind: '$category' } ]).exec(...); 

就最初的问题而言,尝试取消注释上面的第二个阶段,而不是在第一个示例中使用limit(5)