Mongoose模型在种群后得到未定义的属性

我遇到了一个基本要求的问题。 所有我提取的mongoose模型的属性在exec()callback中都是未定义的。

这是我的模式:

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

你可能已经注意到我的“friends”属性是一个引用另一个模式的对象数组。

现在这是我的查询:

 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); } }); 

当这个Web服务返回'_user'时,每个属性都被很好地定义并且具有正确的值。 问题是我只想返回不可能的_user.friends,因为它是未定义的。

现在,这里是apiUtils.jsonResponse函数:

 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)); }; 

和cleanResultsfunction:

 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; }; 

我试图设置超时,看看问题是否来自asynchronous,但它没有改变。 在这个时候我有点沮丧,我想知道你以前是否遇到同样的问题?

我发现你的问题,当你期望只有一个对象被返回时,你不小心使用了find 。 在这种情况下,你应该使用findById

 User .findById(req.session.user._id) .populate('friends._friend', 'name surname picture birthdate') .exec(function(err, user) { ... })