Search code examples
mysqlnode.jsknex.jsbookshelf.js

How to check if email exist with bookshelf and mysql


I have been trying to check if email exist with bookshelfjs, but I always get empty response each time. If I try other fields it works perfectly.

( I prefer if this could work, is there something I am doing wrong?)

var useremail = await Customer.where({ 'email': req.body.email }).fetch({ require: true });

But if I do this I get the right response.

var username = await Customer.where({ 'name': req.body.name }).fetch({ require: true });

I tried this too. fetched all users, then try to get the email, then check if req.body.email exist. but still didnt work

        var emails = await Customer.fetchAll().then(users => {
            users.forEach(element => {
                var emailAlone = element.attributes.email;
                for (const item in emailAlone) {
                    if (item == req.body.email) {
                    console.log("Item is ", item);
                    }
                }
            });
        });

Thanks


Solution

  • I finally fixed like this

    For those might what to do it like this. If there is a better way someone should suggest

          await Customer.where({ 'email': req.body.email }).fetch({ require: true }).then(
                users => {
                    if (users.attributes.email.length > 0) {
                        return res.status(500).json(
                            { error: true, message: "email already exist" }
                        );
                    }
                    else {
                        console.log("registering now");
                       }
    

    I still to see how to check both email and username