【问题标题】:can't call map function on an array of objects in express with mongoose无法使用 mongoose 对对象数组调用 map 函数
【发布时间】:2017-10-09 10:22:09
【问题描述】:

在对象数组上调用 .map 时,会抛出 TypeError 错误:friends.map is not a function。

当我在 vanilla js 中使用对象执行此操作时,它工作正常,但那是在我将 id 和 _id 值括在引号中之后。

这是因为它在 Mongoose 中属于 ObjectId 类型的原因吗?如果是这样,我该如何解决?

var UserSchema = new Schema({
  username   : String,
  firstName  : String,
  lastName   : String
	friends    : [{ id: { type: Schema.Types.ObjectId, ref: 'User'}, status: Number }]
});

app.get('/getFriends', requireLogin, function(req, res) {
  User.findOne({ _id: req.user.id }, 'friends')
  .populate({
    path: 'friends.id',
    model: 'User',
    select: 'username firstName lastName -_id'
  })
  .exec(function(err, friends) {
    console.log(typeof(friends))
    console.log(friends)
    friends = friends.map(function(v) {
      delete(v._id);
      delete(v.status);
      return v;
    });
    res.json(friends);
  }) 
})


events.js:163
      throw er; // Unhandled 'error' event
      ^

TypeError: friends.map is not a function

the output of console.log(friends)

[ { _id: 590bbb88858367c9bb07776e,
    status: 2,
    id: 590bba9c858367c9bb077759 },
  { _id: 590bbb95858367c9bb07776f,
    status: 2,
    id: 590bbad5858367c9bb07775f },
  { _id: 590bbb9e858367c9bb077770,
    status: 2,
    id: 590bbb05858367c9bb077765 },
  { _id: 590bbbaa858367c9bb077771,
    status: 2,
    id: 590bbaf2858367c9bb077763 },
  { _id: 590bbbb6858367c9bb077772,
    status: 2,
    id: 590bbae5858367c9bb077761 },
  { _id: 590bbbc5858367c9bb077773,
    status: 2,
    id: 590bbabe858367c9bb07775d },
  { _id: 590bbbef858367c9bb077774,
    status: 2,
    id: 590bbab2858367c9bb07775b } ]

【问题讨论】:

    标签: javascript express mongoose mongoose-schema


    【解决方案1】:

    在您的代码中,您在 User 模型上调用 .findOne 以查询参数中包含 _id 的文档。

    .findOne 返回单个 mongoose 文档(不是数组),因此 exec 回调中的第二个参数应该引用具有该 _id 的用户,并且只有一个填充的 friends 属性。我不太明白您将如何获得您提供的记录输出。尝试以下方式:

    app.get('/getFriends', requireLogin, function(req, res) {
      User.findOne({ _id: req.user.id }, 'friends')
      .populate({
        path: 'friends.id',
        model: 'User',
        select: 'username firstName lastName -_id'
      })
      .exec(function(err, user) {
        var friends = user.friends.map(function(v) {
          delete(v._id);
          delete(v.status);
          return v;
        });
        res.json(friends);
      }) 
    })
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2021-07-02
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2019-05-24
      • 2021-11-09
      相关资源
      最近更新 更多