कहा जाता है मेरे पास दो एक्सप्रेस मिडलवेयर हैं जहां कोई रेक पर ऑब्जेक्ट सेट कर रहा है और दूसरा इसके बाद उस ऑब्जेक्ट को स्विच स्टेटमेंट चालू करने के लिए उपयोग करता है।req पर ऑब्जेक्ट सेट करना। दो middlwares के पहले में मौजूद नहीं है जब दूसरे मिडलवेयर को
यहाँ एक उदाहरण है: नीचे
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
})
})
टिप्पणियां मुझे आश्वस्त है कि यह एक async मुद्दा नहीं है और परिणाम मुझे लगता है मैं यह क्या हो सकता है पर खो रहा हूँ हो रही है के बाद।
संपादित करें: हालांकि निम्न कार्य करता है, और सत्य दिखाता है। लेकिन _ id felds पर जाँच भी _ id तत्व पर uids.indexOf(req.user._id.toString()) > -1
करने के बाद काम नहीं करता:
newEvent.attending.user.map(obj => {
names.push(obj.name)
})
imAttending = names.indexOf(req.user.name) > -1 // imAttending = true
ऐसा लगता है कि आप एक हल किए गए वादे – marekful
से पहले मिडलवेयर में अगला() को कॉल करना चाहते हैं तो अगला फ़ंक्शन कॉल होने तक मिडलवेयर अगले मध्यवर्ती तक नहीं पहुंच जाएगा। चूंकि आप इसे केवल एसिंक फ़ंक्शन में कॉलबैक में बुला रहे हैं, इसलिए इसे अगले हैंडलर पर जाने से पहले सेट करने के लिए पहले से ही req.user की प्रतीक्षा करनी चाहिए। – DTing
आपका कोड जो आप अभी दिखाते हैं वह केवल डीबी राउंड ट्रिप को पूरा करने और 'req.user' प्रॉपर्टी को सेट करने के बाद 'अगली()' कॉल करेगा। नीचे मेरा जवाब देखें, यह कहीं और समस्या हो सकती है। – Paul