0

I'm currently working on a personal project using so I can mess around with node.js and mongodb as I have never used them before.

I currently have an issue where I cannot figure out how to return either true or false out of the following function:

function checkRefreshToken(token) {
    MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
        if (err) throw err;
        var dbo = db.db("database");
        dbo.collection("collection").findOne({ token: token }, function(err, result) {
            if (err) throw err;
            if (result !== null) {
                db.close();
                return true;
            } else {
                db.close();
                return false;
            } 
        });
    });
}

All the function does is check if a token if present in the collection. However, I cannot return true or false from the function - it always returns undefined. I assume this is because the return is inside of the 'findOne()' function.

What I'm looking for is how to return either true or false so I can use the function like so:

if (checkRefreshToken("abc")) {
    // Do something
}

Thanks :)

P.S sorry if this is an easy fix, like I said this is my first time really using node and mongo

JamiePegg
  • 47
  • 2
  • 7

1 Answers1

1

wrap the code inside function in promise like this

function checkRefreshToken(token) {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
            if (err) throw err;
            var dbo = db.db("database");
            dbo.collection("collection").findOne({ token: token }, function (err, result) {
                if (err) {
                    //throw err;
                    reject(err);
                }
                if (result !== null) {
                    db.close();
                    resolve(true);
                } else {
                    db.close();
                    resolve(false);
                }
            });
        });
    });
}

then make the function async where you are calling this function with await in front of it for eg.

async function() {
    //your code
    const response = await checkRefreshToken("abc");
    if (response) {
        // Do something
    }
}
mss
  • 1,423
  • 2
  • 9
  • 18