0

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?

mohamed adel
  • 695
  • 1
  • 15
  • 36

2 Answers2

1

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.
    }
} )
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • thanks for your answer. the record exists if I do console.log instead of the return all the data will appear. The problem is i think the nested return isn't working – mohamed adel Jan 03 '20 at 23:19
  • 1
    To return a value from an async call, [look here](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). But the only way that you would get the error message you posted, from the code you posted, is if the variable `user` was `null`, which is what that error is telling you. – Alex Wayne Jan 03 '20 at 23:22
0

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)
})
mohamed adel
  • 695
  • 1
  • 15
  • 36