【问题标题】:Object on req.user Undefined (Node, Express)req.user 上的对象未定义(节点,快递)
【发布时间】: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


【解决方案1】:

您的客户端在 req.body.blockedUsers 中传递一个数组,您需要使用 req.body.blockedUsers[0] 作为第一个索引。

如果它不起作用,您可以尝试使用 req.body['blockedUsers[]'][0]

祝你好运。

【讨论】:

  • 感谢您的回答,但它不在 req.body 中。我想我是因为一个错字而误导了你(请参阅我原帖中的 cmets)。
猜你喜欢
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 2018-02-23
  • 2021-06-11
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多