I currently have a problem with my function. I’m using a MongoDB Database to check is something exists and as you can see, if a data value is true, I wanna set the return value of the function to false or when it’s wrong it should return false.
Everything works to this point.
The function is just returning "undefined". I tried everything I could think of and tested atleast one hour but couldn’t find any solution.
I hope anyone of you guys could help me to return a true or false here.
Thanks for your help 😀
Note: Also tried it with async before, didn’t work out
function CheckActiveGamesPlayer1(memberid) {
console.log("3")
db.findOne({ GuildID: guild.id, Player1: memberid }, async(err, data) => {
if (data.Ingame === true) {
console.log("4")
Embed.setDescription(`<@${memberid}> is in an active game. Can't start the game!`).setColor("RANDOM");
channel.send({ embeds: [Embed], ephemeral: true })
return false;
} else {
console.log("5")
return true;
}
})
}
3
Answers
This is not an async function. Your function runs first, returns with undefined.
Then, the async callback is called but that value is passed to nothing.
One way to fix this is to make this an async function, then use "await" keyword.
Try something like this. db.findOne probably returns a promise, so you can do
await db.findOne
instead of providing a callback, then you can return like normal after that.That is because you aren’t actually returning anything in
CheckActiveGamesPlayer1
. However, you are returning something in yourdb.findOne
callback.I am not sure how you are calling the
CheckActiveGamesPlayer1
function, but I would suggest returning aPromise
so you can eitherawait
or.then
it to get the response you’re after.You can then call your function and get the response by
.then
IE:
You can also add
async
to yourCheckActivePlayers1
function so you can just await it.IE:
I am not sure which version of mongo you are working with. But there’s a chance you can just return
db.findOne
as long as that returns a promise. The way you are currently usingdb.findOne
is in the form of a callback, so there would be some code re-arranging if you went this route.https://www.mongodb.com/docs/drivers/node/current/usage-examples/findOne/