1

I really need help with that I spent a lot of time trying to understand that but I don't get it. I'm using nodeJS and MongoDB

I want to do a function that returns true or false depending on if the email is in the database:

I have done that

function isUserRegistered(email) {
    MongoClient.connect(url, function (err, db) {
        if (err) throw err;
        let database = db.db(dataBaseName);
        let query = { "email": email };

        var userCollection = database.collection(collectionName)
        userCollection.find(query).toArray(function (err, result) {
            if (err) throw err;
            db.close();
            if (result.length > 0) {
                return true;
            } else {
                return false;
            }
        });
    });
}

console.log(isUserRegistered("jack@gmail.com").toString());

But when I test it doesn't work because isUserRegistered() is undefined at the time I try to print it. I have tried to do callback functions, and I achieved to print either "false" or "true" with that, but with a callback function, I'm only starting a new function and the isUserRegister() doesn't return a boolean, so I can't do something like that later on my program:

if (isUserRegister(email){
      // Try to login
} else {
     // try to create the account
}

I have also look for async and await, but I don't know where I should use it. Can it be fixed in a simple way?

Thank you

Hamada
  • 1,836
  • 3
  • 13
  • 27
Florent Bouisset
  • 962
  • 1
  • 5
  • 11

1 Answers1

1

The problem is that you can't directly return a value from a callback (see this for more information).

Since the NodeJS MongoClient supports promises out of the box, you can rewrite and simplify your code with async/await very easily. Note that this still needs error handling, but it should give you a start:

async function isUserRegistered(email) {
    const client = await MongoClient.connect(url);

    const db = client.db(dataBaseName);

    const query = {
        "email": email
    };

    const result = await db.collection(collectionName).find(query).toArray();

    if (result.length > 0) {
        return true;
    } else {
        return false;
    }
}

(async () => {
    console.log(await isUserRegistered("jack@gmail.com"));
})();  
eol
  • 23,236
  • 5
  • 46
  • 64
  • thank you so much it's working perfectly, I spend so much time on this ! So if I simplify a bit I need to put await before function that may take time ? – Florent Bouisset Jun 20 '20 at 13:22
  • Happy to help! Not quite - the correct way to phrase it is: you can use `await` on an asynchronous function that returns a promise ;) Here's some nice information about that: https://javascript.info/async – eol Jun 20 '20 at 13:27
  • Ok I got it, but how do you know that mongoClient.connect return a promise ? On the documentation https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html it says that connect return null, or maybe it's not up to date ? – Florent Bouisset Jun 20 '20 at 13:48
  • Seems like you're on an outdated version of the library, here's the link to the latest one: https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#.connect – eol Jun 20 '20 at 13:53
  • Ok thanks ! have a good day – Florent Bouisset Jun 20 '20 at 13:58
  • Hey, giving you some news, that things was part of an 'exercice' I had to do in order to apply to an internship. I was a novice in javascript so thank you ! I've been hired :) – Florent Bouisset Sep 09 '20 at 18:20
  • Oh that's great news, congratulations! :) – eol Sep 09 '20 at 19:25