I have two models : User
, associated by a one-to-many reference with Member
.
I want to retrieve the firstName & lastName of User
from the Member
model, so that I've added a function getName
to Member
, that would first populate the 'user' field and then return a value when invoked from a template like this :
<p><%= data.members[i].getName() %></p>
But I only get "undefined" in the template (whereas I can print the good values in console from inside the getName function). I guess this is due to the fact that since I have to query the base, getName is going async and returns a Promise.
Here are my models :
/**
* User.js
*/
module.exports = {
attributes : {
firstName : 'string',
lastName : 'string',
}
}
/**
* Member.js
*/
module.exports = {
attributes : {
user : {
model : 'User'
},
getName: function() {
return Member
.findOne({ id : this.id })
.populate('user')
.exec(function(err, member) {
if(err) return err;
return member.user.firstName +' '+ member.user.lastName;
});
}
}
}
Can someone help me by telling me what is wrong with my code ?
P.S. : This might be solved by populating the 'user' field from the controller instead of from the model, but I have another issue like this one that would follow the same principles.