2017-05-10 28 views
0

在对象数组上调用.map时,会抛出TypeError错误:friends.map不是函数。不能在对象数组上使用猫鼬快速调用map函数

当我在对象的香草js中使用它时,它工作正常,但是在将id和_id值括在引号中之后。

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

var UserSchema = new Schema({ 
 
    username : String, 
 
    firstName : String, 
 
    lastName : String 
 
\t 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 } ]

回答

1

在你的代码,你就User模型调用.findOne来查询与在PARAMS的_id的文件。

.findOne返回单个猫鼬文档(不是数组),因此exec的回调中的第二个参数应该引用具有该_id的用户,并且仅具有已填充的朋友属性。我不太清楚你将如何获得你提供的记录输出。尝试沿着这些线路:

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