0

I am trying to check weather an account associated with the same username already exists or not. I am using the exist method to check but I keep getting a large object instead of a Boolean value.

async checkExisting(username,userCollection) { //WORK ON ISSUE WITH VERIFYING
        const check = new Promise((resolve,reject) => {
            let value = userCollection.exists({username})
            console.log(value);
            // if(userCollection.exists({username})) {
            //     reject("Username taken")
            // }

            resolve("Username avaliable")
        })

        return check;
    },
  • Please show us the value of the "*large object*" that you printed. It should be pretty clear what it represents and where the mistake is. – Bergi Jan 02 '23 at 02:57

2 Answers2

1

Your code is correct. It's just what you write in resolve is returned. And no need to make the function async as you're already returning a Promise. So where you call this function there just keep await as follows

await checkExisting('username', 'collection')

checkExisting(username, userCollection)
{
 return new Promise((resolve, reject) => {
  userCollection
   .exists({username})
   .then((value) => {
    if (value) {
     resolve(true)
    }
    resolve(false)
   })
   .catch((err) => reject(err))
 })
}

Note: You can use either promise or async-await syntax; both ways are correct. However, never combine these two concepts as it will give unexpected output.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Vats Patel
  • 11
  • 2
0

userCollection.exists({username}) returns a query that you never ran. You need to actually execute it and wait for the result. Also avoid the Promise constructor antipattern. Just do

async checkExisting(username,userCollection) {
    const check = await userCollection.exists({username})
    if (check) {
        throw new Error("Username taken");
    }
    return "Username avaliable";
},
Bergi
  • 630,263
  • 148
  • 957
  • 1,375