【发布时间】:2016-11-01 06:39:00
【问题描述】:
我正在尝试访问 req.user 对象上名为 blockedUsers 的数组,但它返回未定义。 req.user 上还有其他数组和键/值对,我可以毫无问题地访问所有这些。
如果我console.log(req.user);,那么我会得到以下信息:
{ _id: 57ebbdedf814b103c81e0b3d,
// ... loads of other key:value pairs ...
lastLogin: 1477934742883,
__v: 0,
blockedUsers: [ '57ebcca8f814b103c81e0b4f' ], // This is the one I want to access!
comMethod: [ 'face to face', 'email', 'whatsapp', 'skype' ],
photos:
[ '/uploads/1fb7f43df2eecafb01138230c6cd87351475067373516.jpeg',
'/uploads/3398bcddd39be966e8300a8b9f252b181475067373518.jpeg' ] }
我可以访问任何其他属性,但不能访问blockedUsers。
我试过JSON.stringify(req.user.blockedUsers);,但它仍然未定义。
当我将对象添加到数据库中的用户时,我也尝试过 JSON.stringifying 对象,我得到了相同的结果。
如果有帮助,这里是我将blockedUsers添加到数据库中的用户的代码:
app.post('/users/block', function(req,res){
User.findByIdAndUpdate(
req.body.blockingUser, // the id of the user doing the blocking
{$push: {blockedUsers: req.body.blockedUserId}}, // the id of the user being blocked
{upsert: true},
// ... error handling and res.redirect - this all seems to work fine
我看不出blockedUsers 和req.user 的其他属性之间有什么区别,我一遍又一遍地检查拼写错误和其他简单的错误。任何指导将不胜感激!
【问题讨论】:
-
我很抱歉,但我很困惑,你想访问
req.user.blockedUsers,但你试图字符串化req.body.blockedUsers,只是你需要尝试req.user而不是@987654328 @? -
啊,谢谢!那只是一个错字——我的意思是“stringify req.user.blockedUsers”。我会更新我的问题。
-
blockedUsers是一个数组吗? -
没错@adeneo。
findByIdAndUpdate正在寻找一个完全不同的_id,而我的那部分代码工作正常。
标签: javascript arrays node.js express passport.js