2

我遇到了一个基本请求的问题。我获取的猫鼬模型的所有属性都未在 exec() 回调中定义。

这是我的架构:

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

您已经注意到我的“朋友”属性是一个引用另一个模式的对象数组。

现在这是我的查询:

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

还有 cleanResults 函数:

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

我尝试设置超时以查看问题是否来自异步,但它没有改变。我现在有点绝望,我想知道你以前是否遇到过同样的问题?

4

1 回答 1

3

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

User
    .findById(req.session.user._id)
    .populate('friends._friend', 'name surname picture birthdate')
    .exec(function(err, user) {
        ...
    })
于 2014-09-15T09:29:23.100 回答