node.js - Mongoose 模型在填充后获得未定义的属性

标签 node.js mongodb mongoose swagger mongoose-populate

我在基本请求方面遇到了问题。 我获取的 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;
};

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

最佳答案

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

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

关于node.js - Mongoose 模型在填充后获得未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838007/

相关文章:

mongodb - 在 mongodb 聚合管道中创建价格范围方面

node.js - Mongoose - 转换为 ObjectId 失败,路径 _id 处的值为 "[object Object]"

javascript - MongoDB 对象不更新

html - Angular 和 Node JS 中的路由问题 [angular]

mysql - 在 MySQL 数据库 Nodejs 中存储 JSON 数组

javascript - Promises.all() 在具有 'promised' 属性的对象数组上

javascript - 为什么我的 LoopBack/Node 应用程序无法获取 Bluemix 中部署的工具链上的环境变量?

mongodb - mongoDB 在进行多键查找方面效率高吗?

MongoDB 转义数据库名称中的特殊字符

node.js - Mongoose 异步请求管理