Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 370
S. Schenk Avatar asked Oct 08 '16 13:10

S. Schenk


People also ask

Is there a limit on defining number of middlewares when writing the server app using Express?

Yes they are infinitely chainable, AFAIK Express takes the first argument to 'get' as the pattern match, and all subsequent arguments are middlewares. As coded your middleware will always send a response, so no following middlewares will ever be run.

What should you call at the end of your middleware function?

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging. The following figure shows the elements of a middleware function call: HTTP method for which the middleware function applies.

What is middleware in Express JS What are the different types of middleware?

Middleware functions in Express are of the following types: Application-level middleware which runs for all routes in an app object. Router level middleware which runs for all routes in a router object. Built-in middleware provided by Express like express.

What are the middlewares in node JS?

The middleware in node. js is a function that will have all the access for requesting an object, responding to an object, and moving to the next middleware function in the application request-response cycle.


1 Answers

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.

like image 106
Paul Avatar answered Sep 30 '22 21:09

Paul