0

I have the following code;

if (checkUserExists(serverID, userID) === null) {
    console.log("was null");
    addNewUserToDB(serverID, userID, username);
} 

I want it to execute if mongoDB doesn't find a match for the Server & UID. Therefore, I have this;

function checkUserExists(serverID, userID) {
    mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});

    playerModel.findOne({"serverID": serverID, "userID": userID }, (err, player) => {
        if (err) {
            console.log(err);
        } else {
            console.log(player);
            return player;
        }
    });
}

If there's a found user, it returns the user object. If there isn't, it returns the object, which will be null. However, the if statement never triggers.

  • Am I right to assume that conole.log(player) does not display aswell? – Gloat Nov 30 '19 at 09:56
  • The 'was not null'? Yeah, it doesn't display. –  Nov 30 '19 at 10:00
  • The issue, in short, is that `checkUserExists` always returns `undefined` not `null`. Note that the `return` statements are not `return`ing from `checkUserExists`, but the inner callback function passed to `findOne`. Your code is asynchronous, see the duplicate I mentioned for a variety of techniques to handle this. – Robin Zigmond Nov 30 '19 at 10:02
  • Thank you so much, I'm relatively new to JS so that was a great help. –  Nov 30 '19 at 10:50

1 Answers1

0

Your code executes asynchronously inside checkUserExists method, That's why checkUserExists returns nothing. Use async/await to wait for the response from finOne then return response.

Example

async function checkUserExists(serverID, userID) {
  mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });
  var response;
  try {
    response = await playerModel.findOne({"serverID": serverID, "userID": userID});
    return response;
  } catch (e) {
    // Error handling
    response = { "title": "error in retrieving players", "desc": ""};
    return response;
  }
}
hbamithkumara
  • 2,344
  • 1
  • 17
  • 17