I appreciate some help. I'm doing an api rest with express and mongodb (v3.4.4), using mongoose (v4.10.5). I need to do an aggregation operation, but I do not deal with it. I show you some code. The models (it has more properties, but I have left it simple):
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 }
}));
Important, I'm interested in populate category
field of MyModel
, not other
field.
Suppose Category
and MyModel
has certain records well formed. The request:
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
is correct, has 5 records, but not include category
. Now, I try with:
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);
});
Now data
is empty. I set mongoose.set('debug', true);
and the operations they look right, inclusive the last operation aggregate
, but data is empty...
I do not know if I explained well. Obviously there is something that I am not fully understanding. Thanks in advance.