【发布时间】:2018-01-30 01:29:07
【问题描述】:
感谢您的帮助。我正在使用 mongoose (v4.10.5) 使用 express 和 mongodb (v3.4.4) 进行 api 休息。我需要做一个聚合操作,但我不处理它。我给你看一些代码。模型(它有更多属性,但我保持简单):
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 }
}));
重要的是,我有兴趣填充 MyModel 的 category 字段,而不是 other 字段。
假设Category 和MyModel 有某些格式良好的记录。请求:
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 条记录,但不包括 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,但是数据是空的...
我不知道我解释得好不好。显然,有些事情我并不完全理解。提前致谢。
【问题讨论】:
标签: node.js mongodb express mongoose aggregate