I got a problem for a basic request. All properties of a mongoose model I fetch are undefined in the exec() callback.
Here is my schema :
userSchema: new Schema({
email: { type: String, limit: 50, index: true },
password: String,
birthdate: { type: Date },
active: { type: Boolean, default: true },
friends: [{
_friend: { type: Schema.ObjectId, ref: 'User' },
addedDate: { type: Date, default: Date.now }
}],
registrationDate: { type: Date, default: Date.now }
})
You can already notice that my "friends" property is an array of objects referencing another schema.
Now here is my query :
dbModels.User
.find({ _id: req.session.user._id })
.populate('friends._friend', 'email birthdate')
.exec(function (err, _user){
if (err || !_user){
apiUtils.errorResponse(res, sw, 'Error when fetching friends.', 500);
} else {
console.log('user', _user);
// This output the object with all its properties
console.log('user birthdate', _user.birthdate);
// _user.birthdate is undefined
console.log('user friends', _user.friends);
// _user.friends is undefined
apiUtils.jsonResponse(res, sw, _user);
}
});
When this web service return '_user', each properties are well defined and have the correct values. The problem is that I only want to return _user.friends which is not possible since it's undefined.
Now, here is apiUtils.jsonResponse function :
exports.jsonResponse = function (res, sw, body) {
console.log(body.friends);
// At this breakpoint, body.friends is still undefined
(sw || _sw).setHeaders(res);
if (util.isArray(body)) {
for (var i = 0; i < body.length; i++) {
body[i] = exports.cleanResults(body[i]);
}
} else {
console.log(body.friends);
// At this breakpoint body.friends is still undefined
body = exports.cleanResults(body);
}
res.send(httpCode || 200, JSON.stringify(body));
};
And the cleanResults function :
exports.cleanResults = function (body) {
console.log(body.friends);
// At this point, body.friends is FINALLY DEFINED
if (typeof body.toObject === 'function') {
body = body.toObject();
delete body.__v;
}
for (var attr in body) {
if (body.hasOwnProperty(attr) && attr[0] == '_') {
var _attr = attr.replace('_', '');
body[_attr] = body[attr];
delete body[attr];
}
}
return body;
};
I tried to set a timeout to see if the problem came from async but it changed nothing. I'm a bit desesperate at this time and I wanted to know if you already encountered the same problem before ?
I see your problem, you have accidentally used find when you expect only one object to be returned. In this case, you should use findById:
User
.findById(req.session.user._id)
.populate('friends._friend', 'name surname picture birthdate')
.exec(function(err, user) {
...
})