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