Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a mongoose virtual field that lists the length of a subdocument?

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

like image 600
Nodernaut Avatar asked Nov 11 '22 14:11

Nodernaut


1 Answers

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).

like image 65
WiredPrairie Avatar answered Nov 15 '22 06:11

WiredPrairie