dimanche 29 mars 2015

Virtual getter with business logic and populate

I have a virtual like this:



User.virtual('weaknesses').get(function () {
var weaknesses = [];

for (index = 0; index < this.natural.weaknesses; index++) {
weaknesses.push(getRandomWeakness(this.natural.weaknesses));
};

return weaknesses;
});


And when I populate:



Workspace
.findOne({ stage: request.params.stage })
.populate('user', 'name weaknesses')
.exec(function (error, workspace) {
if (error) {
response.status(404).send('Not found');
};

response.send(workspace);
});


The weaknesses isn't there, being displayed.


According to this thread, this happens because weaknesses has a dependency on it—apparently occurring because of my business logic to getRandomWeakness().


The point is: the author of the answer said:



By the way, you should not implement business logic inside virtual getters to avoid situations like this. consider creating another virtual.



What does he meant with "consider creating another virtual"? Is this a real solution and if so, how can I reach it?


And before you ask, I already have the necessary schema options to handle with virtuals:



// [...]
{
toJSON: {
virtuals: true
}
}
// [...]

Aucun commentaire:

Enregistrer un commentaire