我欣赏一些帮助。我正在用express和mongodb(v3.4.4)做一个api rest,使用猫鼬(v4.10.5)。我需要做一个聚合操作,但我没有处理它。我给你看一些代码。该模型(它有更多的属性,但我已经离开它简单):如何使聚合+填充猫鼬
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
,但是数据是空的...
我不知道我是否解释得很好。显然有一些我不完全理解。提前致谢。
谢谢,但不工作。我试着用'from:'Category'','localField:'category''和其他组合,我在数组中包含'$ limit',并且没有'$ unwind' ......总之,有几十个组合。另外,为什么需要光标?我不明白。请注意,我要填充的字段是“MyModel”的“类别”,而不是“_id”。再次感谢。 – lmfresneda
@LuisMiguelF。啊,你说得对,它应该是'category'。你不应该需要'cursor()'如我的例子所示。我还会设置[debug on](http://mongoosejs.com/docs/faq.html#enable_debugging)来查看任何查询。用类别模式编辑您的问题。你是否也在运行MongoDB v3.2或更高版本? – Mikey
对不起@Mikey,光标是我的错,我在这个测试中用Mockgoose代替Mongoose(尽管我不知道为什么Mockgoose需要一个游标)。现在,我只使用猫鼬,我会编辑我的问题。还是不行... :( – lmfresneda