I have this function
const run = async () => {
await LOLUserData.LOLUserData(3)
const LOLUserDataResult = await LOLUserData.LOLUserData()
console.log(LOLUserDataResult)
await app.listen(PORT, () => {
console.log(`Arena Gaming Server is listening on port ${PORT}!`)
})
}
which sends data to this function on startup
//=============================================================================
// [Mongoose] Get Active Sessions users data [userId, IGN, LOLSummonerId, LOLRegion] {Step (2)} {League of Legends Tracking}
//=============================================================================
const User = require('../../models/user')
const getLOLUserData = (userId) => {
// Get User data if (valid userId & IGN exsists)
User.findOne({'userId': userId, $and: [ { IGN: { $ne: '' , $exists: true} } ]})
.then(user => {
return ( [
user.userId,
user.IGN,
user.LOLRegion,
user.LOLSummonerId
])
} )
.catch(err => {
console.log(err)
})
};
exports.LOLUserData = getLOLUserData
The const LOLUserDataResult = await LOLUserData.LOLUserData()
console.log(LOLUserDataResult)
Should return the array from the previous function but instead i get an error
TypeError: Cannot read property 'userId' of null
What am I doing wrong here?
2 Answers 2
It looks like User.findOne()
is not finding a record that matches your query. The query successfully executes, but finds no results. The promise resolves to null
, indicating no record was found. Your then()
callback runs, and tries to access user.userId
, which is null.userId
, which throws the exception.
In your then()
callback, you should probably have something like this, to protect against getting no results.
.then(user => {
if (user) {
return [
user.userId,
user.IGN,
user.LOLRegion,
user.LOLSummonerId
]
} else {
return [] // or whatever makes sense.
}
} )
2 Comments
user
was null
, which is what that error is telling you.The solution was adding a callback argument and returning it
const getLOLUserData = (userId, callBack) => {
// Get User data if (valid userId & IGN exsists)
User.findOne({'userId': userId, $and: [ { IGN: { $ne: '' , $exists: true} } ]})
.then(user => {
let result = [
user.userId,
//user.IGN,
user.LOLRegion,
user.LOLSummonerId
]
return callBack(result)
})
.catch(err => {
console.log(err)
})
};
And in app.js I can use it like this
await LOLUserData.LOLUserData(3, async (result) => {
console.info(result)
})