Returning boolean from mongoose .exists function

I’m trying to learn some node.js and mongoDB. I’m writing a demo login system to that end.

I have a function called by my main api to check in the mongoDB whether a refreshToken exists.

const checkRefreshTokenDB = (tokenPayload) => {
  const decoded = jwt.decode(tokenPayload);
  RefreshToken.exists(
    { tokenId: decoded.refresh.tokenId },
    function (err, result) {
      if (err) {
        console.log(err);
      } else {
        console.log('Result: ' + result);
      }
    }
  );
};

I can see the RefreshToken.exists is working find in the console.log. What I’m struggling with is making this function return a simple true/false to the caller. At the moment it seems to be returning a promise.

Any help would be very appreciated Thanks

Answer

One way to resolve the issue is by using async/await.

const checkRefreshTokenDB = async (tokenPayload) => {
  const decoded = jwt.decode(tokenPayload);
  return await RefreshToken.exists({ tokenId: decoded.refresh.tokenId });
};

Now you can call this function as shown below from an async function (await is only valid in async function)

const status = await checkRefreshTokenDB(tokenPayload);
console.log(status)