S. *_*enk 6 javascript mongoose mongodb express
我有两个快速的middlware,其中一个是将对象设置为req,另一个是跟随它使用该对象来转换switch语句.
这是一个例子:
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
})
})
Run Code Online (Sandbox Code Playgroud)
下面的评论让我放心,这不是一个异步的问题,并且结果我得到的结果是我迷失了.
编辑:以下工作,但显示为true.但是,即使uids.indexOf(req.user._id.toString()) > -1对_id元素进行操作,检查_id felds也不起作用:
newEvent.attending.user.map(obj => {
names.push(obj.name)
})
imAttending = names.indexOf(req.user.name) > -1 // imAttending = true
Run Code Online (Sandbox Code Playgroud)
由于问题中提供了附加信息,决定添加另一个答案。
看起来您正在使用 MongoDB 和 Mongoose(如果我是对的,它们应该在标签中)。鉴于此,用户文档的_id属性将不等于它的字符串形式,因为表示实际上是ObjectID('blahblahblah'),它实际上并不是一个字符串。如果你console.log()这样做,它将看起来像一个字符串,因为 console.log 在其底层调用了 toString() 。
因此,您可能想要尝试的评估是:
imAttending = uids.indexOf(req.user._id.toString()) > -1;
console.log(imAttending); // should be true
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这也是为什么使用诸如node-inspector设置断点和单步调试代码之类的东西,而不是依赖控制台语句来调试的一个重要原因。您将看到各个位的实际表示,而不是它们的字符串化形式。
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |