Placing an item on req in the initial middleware does not appear to be available when the second middleware is executed

Dealing with two express middlewares, where the first one sets an object to the req and the second one uses that object in a switch statement.

Let's break it down:

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
          })
        })

Despite confirming it's not due to async issues in the comments below, I'm still puzzled by the unexpected results.

Edit: However, this part works fine and returns true. But when cross-checking using the _id field, even after converting using

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

Answer №1

Opted to provide an additional answer due to the new details offered in the question.

It appears that MongoDB and Mongoose are being used (should be included in the tags if correct). In this case, a user document's _id property will not match its string form as it is actually represented as ObjectID('blahblahblah'), not a string underneath. When you console.log() it, it may appear as a string because console.log calls toString() internally.

Therefore, the evaluation you should consider is:

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

Additionally, this highlights the importance of using tools like node-inspector for setting breakpoints and debugging your code, rather than solely relying on console statements. This allows you to view the actual representations of different elements instead of their stringified versions.

Answer №2

The problem was actually with the toString() function. The data retrieved from the database may not always match the expected data type.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Redirecting to a specific mobile page using Javascript

I'm looking for a way to redirect users to different versions of my website based on their browser size. Currently, I have the following script in place: <script> if (screen.width <= 1024) window.location.replace("http://www.website.com/") e ...

Brochure displaying shattered tiles using ionic

Whenever I try to load a map using Ionic, it keeps displaying broken tiles. No matter if I load directly from Leaflet or use bower, the issue persists. Even when using pure leaflet code without any special directives, those broken tiles are still there. ...

Why doesn't Select2 function properly in Bootstrap 3 when the tabindex is removed?

There is a bug with Select2 that causes it to malfunction in a Bootstrap 3 modal unless the tabindex element is removed. I have successfully resolved this issue in several modals on my page, but one specific modal still cannot get Select2 to function. Eac ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Unable to programmatically modify the src attribute on embed player - experiencing issues

I have been attempting to modify the src attribute in order to play a YouTube video using JavaScript, but so far I haven't had any success. Here is the code snippet I've been trying to use: $("#youtube-player").setAttribute('src', obj ...

Organizing numbers in Chrome using Array.sort()

While attempting to reorganize an array of divs based on their positions relative to each other, I encountered a peculiar issue. After spending considerable time troubleshooting in CodePen, it became apparent that Chrome's sorting behavior gets errati ...

How do I send multiple values from a child to a parent in Vue.js, while also passing another parameter in the parent's v-on event?

Behold, a demonstration of code. Vue.component('button-counter', { template: '<button v-on:click="emit_event">button</button>', methods: { emit_event: function () { this.$emit('change', 'v1&apos ...

Employing HTML5/CSS3 for classic image animation through traditional Sprite animation techniques

Currently, I am exploring the use of a sprite sheet for animation purposes. Rather than using canvas, I have opted for the HTML5/CSS3 method of displaying images on the screen. However, I have encountered a potential obstacle at the start of this process. ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Attempting to deploy my node.js application on Heroku resulted in an error message saying that the web process failed to bind to $PORT within 60 seconds of launch, causing the process to exit with status

I recently encountered an issue while attempting to deploy my node.js app on Heroku. The error message stated that the Web process failed to bind to $PORT within 60 seconds of launch, and the Process exited with status 137. I'm unsure of how to resolv ...

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

Simplifying parameter types for error handling in app.use callback with Express.js and TypeScript

With some familiarity with TypeScript but a newcomer to Express.js, I aim to develop a generic error handler for my Express.js app built in TypeScript. The code snippet below is functional in JavaScript: // catch 404 and forward to error handler app.use((r ...

Troubleshooting a lag in Spring Data MongoDB's efficiency

I encountered a problem with spring data mongodb while working on a method that performs a simple "find" operation, retrieving approximately 1000 documents. Below is my spring data code snippet: Query myquery = query(where("ipp").is(ipp).and(CODE_MESURE). ...

StopPropagation() method in Ng-class not functioning properly in Angular for parent element

I am facing an issue with 2 nested ng-repeats. The parent one is supposed to add a class based on ng-click, but even when I click the child, it still triggers when I don't want it to. <div class="add-filter-tags" data-filter="{{f1}}" ng-class="{&a ...

Discovering the properties in an object using a variable name in JavaScript

I am sending my string to the function below. $scope.sort= function(query){ console.log(query); // returns "name"; $scope.resultset.sort(function(a, b) { return parseFloat(b.query) - parseFloat(a.query); //returns undefined; }); }; wher ...

Ways to consistently press a particular button every single second

The code on the webpage looks like this: <div id="content"> <div class="container-fluid"> Slots <p>The current jackpot is 23220!<p/> <p>You lose.</p> <form method=post action=/game ...

What is the maximum duration we can set for the Ajax timeout?

I am facing a situation where an ajax request can take between 5-10 minutes to process on the server side. Instead of continuously polling from JavaScript to check if the request is completed, I am considering making just one ajax call and setting the tim ...