I'm trying to do aggregations on Mongoose schemas that use the newer virtual populate functionality (using Mongoose 4.13, Mongo 3.6).
Lets say I have the following (simplified for illustration purposes) schemas:
const ProjectSchema = new mongoose.Schema({
projectId: Number,
description: String
});
ProjectSchema.virtual('tasks', {
ref: 'Task',
localField: 'projectId',
foreignField: 'projectId'
justOne: false
]);
const TaskSchema = new mongoose.Schema({
taskId: Number,
projectId: Number
hours: Number
});
const Project = mongoose.model('Project', ProjectSchema);
const Task = mongoose.model('Task', TaskSchema);
Querying on Project and populating relating tasks is working fine using .populate() like:
Project.find({projectId: <id>}).populate('tasks');
But now I would like to sum the hours on tasks by project (left the $sum part out below btw..). I'm only getting empty arrays back no matter what. Isn't it possible to aggregate with virtual populate or?
const result = await Project.aggregate([
{ $match : { projectId: <id> } },
{ $lookup: {
from: 'tasks',
localField: 'projectId',
foreignField: 'projectId',
as: 'tasks'
},
{
$unwind: '$tasks'
}
}
]);