Home > front end >  How do we retrieve a Boolean with exists in mongoose?
How do we retrieve a Boolean with exists in mongoose?

Time:01-02

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;
    },

CodePudding user response:

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";
},

CodePudding user response:

What's the issue between Object and Boolean value?

  • You can check whether the user with this username exists or not by checking !!userCollection.findOne({username}).
  • You can use static methods in mongoose to wrap it up and make it reusable!

I catch a lot of devs use this, so I think it very normally.

  • Related