首页 文章

Mongoose模型在填充后获得未定义的属性

提问于
浏览
2

我遇到了基本请求的问题 . 我获取的mongoose模型的所有属性在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 }
  })

您已经注意到我的“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));
};

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

我试图设置一个超时,以查看问题是否来自异步,但它没有改变任何东西 . 我此时有点沮丧,我想知道你以前是否遇到过同样的问题?

1 回答

  • 3

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

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

相关问题