Pretty new to mongo and I can't figure out what approach is best to do a join on my referenced data. I'm unsure if I should do two pulls.
I have a node application that runs mongoose. It's a collection of agenda items and each item has tasks.
Here is the info on the relevant schemas:
Agenda Schema:
var agendaSchema = new mongoose.Schema({
type : {type: String, required: true},
description : {type: String, required: true},
status: { type: String, enum: ['New', 'Assigned', 'Closed'], required: true },
followup: {type: Date},
created: {type: Date, default: Date.now()},
assigned : String,
crq_nbr : Number,
tasks : [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Task"
}
]
});
Task Schema:
var taskSchema = mongoose.Schema({
created : { type: Date, default: Date.now },
completed : { type: Date, default: Date.now },
status: {type: String, enum: ["Open","Closed"]},
author: {
id : { type: mongoose.Schema.Types.ObjectId, ref: "User" },
name: String
},
text : String,
updated : Date
});
I'm trying to pull all Agenda items that have task that is "completed" status.
One idea I had was to pull all agenda items, populate them based on a $match. After that I would filter out any agenda items that do not have a task in it using javascript.
Ex: (Still have to add the $date condition)
Agenda.find({}).populate({
"path": "tasks",
"match": {"status" : "Closed"}
}).exec(function(err, foundAgenda) {
let newAgenda = foundAgenda.filter(function(agenda) {
if (agenda.tasks.length > 0) return true;
})
res.send(newAgenda);
});
Another horrible idea I had was to find all tasks and find the ID's then findthe agenda based on those IDs and populate it. The problem with this is not only is it two seperate queries
Task.find({ "status": "Closed"}, { _id: 1 }, function(err, foundTasks) {
if (err) {} else {
var taskArray = [];
foundTasks.forEach(function(task) {taskArray.push(task)});
Agenda.find({"tasks" : {$in : foundTasks}}, function(err, foundAgenda) {
res.send(foundAgenda);
});
}
});
Both of these might work for me but I'm sure there are better ways. What's the best approach for this type of join?