I have a node.js REST api route which returns projects objects as json minus the tasks:
exports.list = function(req, res) {
return Project.find(null,'-tasks',null,function(err, projects) {
if (!err) {
return res.json(projects);
} else {
return res.send(err);
}
});
};
This is intended to be used for navigation elements that list all projects but won't be needing the individual tasks (which number in the 100s). This works well but now I need to include a count of the number of tasks in the navigation so I added this to my model:
var ProjectSchema = Schema({
name : String,
tasks : [{
name : String,
state : String }]
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
ProjectSchema.virtual("taskCount").get(function(){
return this.tasks.length;
});
But I get the following error: TypeError: Cannot read property 'length' of undefined
Because you're excluding tasks
, the virtual property cannot check the length
of the property (as it's not defined).
Either include tasks
, or include the length as a precomputed value of your schema. You could just use $inc
on the field to change the length as new items are added to the array of tasks (or just set it directly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With