Tuesday, October 18, 2016

Setting an object on req. in the first of two middlwares seems to not be present at the time the second middlware is called

Leave a Comment

I have two express middlwares where one is setting an object to the req and the other that follows it uses that object to turn a switch statement.

Here's an illustration:

module.exports = (req, res, next) => {   if (!req.headers.authorization) {     return res.status(401).end()   }   const token = req.headers.authorization.split(' ')[1]   return jwt.verify(token, config.database.jwtSecret, (err, decoded) => {     if (err) { return res.status(401).end() }      const userId = decoded.sub     return User.findById(userId, (userErr, user) => {       if (userErr || !user) {         return res.status(401).end()       }       req.user = {         _id: user._id,         name: user.name       }       return next()     })   }) }      //My route         userpage.get('/', authCheck, (req, res) => {           return Event.findOne()           .populate('attending.user', 'name')            .exec((err, newEvent) => {             if (err) {               console.log(err)               res.status(400).end()             }             let uids = []             let imAttending = false             newDinner.attending.user.map(obj => {               uids.push(obj._id)               })             console.log(uids) // Shows the array with all uids             // Double checked that it is indeed an array             let isArr = Object.prototype.toString.call(uids) === '[object Array]'             console.log(isArr) // true             console.log(req.user._id) // Shows the id and it's indeed matching one of the ids in the uids array             imAttending = uids.indexOf(req.user._id) > -1             console.log(imAttending)  // false <--- Should be true             // Test             let id = '57ec2203ba3e994c7c9d5832' // I litraly copy pasted that from the console.log(req.user._id)             imAttendingII = uids.indexOf(id) > -1             console.log(imAttendingII) // true ???? what the heck?             // checking it's the same type as suggested in one of the comments             let check = ['57ec2203ba3e994c7c9d5832'].indexOf(req.user._id) === -1             console.log(check) //true           })         }) 

The comments below reassured me that it's not an async issue and following the results I'm getting I'm lost at what it could be.

Edit: The following works though, and shows true. But checking on the _id felds doesn't work even after doing uids.indexOf(req.user._id.toString()) > -1 on the _id element:

newEvent.attending.user.map(obj => {       names.push(obj.name)     })     imAttending = names.indexOf(req.user.name) > -1 // imAttending = true 

2 Answers

Answers 1

Decided to add another answer because of the additional information provided in the question.

It looks like you're using MongoDB and Mongoose (which should be in the tags if I'm right). Given that, a user document's _id property will not be equal to the string form of it, because the representation is actually ObjectID('blahblahblah'), it's not actually a string under the hood. If you console.log() it, it will look like a string because console.log calls toString() under its hood.

So the evaluation you might want to try is:

imAttending = uids.indexOf(req.user._id.toString()) > -1; console.log(imAttending); // should be true 

As a side note, this is also why it's a great reason to use something like node-inspector to set breakpoints and step through your code, rather than relying on console statements to debug. You'll see the actual representation of the various bits, rather than their stringified form.

Answers 2

It was an issue of toString() all along. The results you get back from querying the db are not necessarily the type you think it might be.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment