简体   繁体   English

req.user上的对象未定义(节点,Express)

[英]Object on req.user Undefined (Node, Express)

I'm trying to access an array called blockedUsers on a req.user object, however it comes back undefined. 我正在尝试访问req.user对象上的名为blockedUsers的数组,但是它返回时未定义。 There are other arrays and key/value pairs on req.user, all of which I can access without problems. req.user上还有其他数组和键/值对,我可以毫无问题地访问所有这些数组和键/值对。

If I console.log(req.user); 如果我console.log(req.user); then I get the following: 然后我得到以下内容:

{ _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' ] }

I can access any of the other properties, but not blockedUsers. 我可以访问任何其他属性,但不能访问blockedUsers。

I've tried JSON.stringify(req.user.blockedUsers); 我已经尝试过JSON.stringify(req.user.blockedUsers); , and it still comes back undefined. ,但仍返回未定义状态。

I've also tried JSON.stringifying the object when I add it to the user in the DB, and I get the same result. 当我将对象添加到数据库中的用户时,我也尝试过JSON.stringifying对象,并且得到相同的结果。

In case it's helpful, here's the bit of code where I add blockedUsers to the user in the database: 如果有帮助,请在下面的代码中将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

I can't see what the difference is between blockedUsers and the other properties of req.user, and I've checked over and again for typos and other simple mistakes. 我看不出blockedUsers和req.user的其他属性之间的区别是什么,我已经一遍又一遍地检查错别字和其他简单的错误。 Any guidance would be appreciated! 任何指导将不胜感激!

Your client-side are passing an array in req.body.blockedUsers, you need to use req.body.blockedUsers[0] for the first index. 您的客户端正在传递req.body.blockedUsers中的数组,您需要将req.body.blockedUsers [0]用于第一个索引。

If it dont working, you can try use req.body['blockedUsers[]'][0] 如果不起作用,您可以尝试使用req.body ['blockedUsers []'] [0]

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM