Siddhartha Chowdhury
Siddhartha Chowdhury

Reputation: 2732

Sails.js. Check if user exists

Hello guys am new to Sails.js ( using MySQL ) Am trying to find if a user already exists before registration.

Here this is the code:

register:function(req, res, next){
    var params = req.params.all();

    User.find({
        or : [
            { usrnm:params.usrname },
            { eml:params.eml }
        ]
    })
    .exec(function (err, user){
        if (err) {
            return res.negotiate(err);
        }
        if (user) {
            res.status(400);
            return res.json('User already exists!');
        }
    });

    User.create(params, function(err, user){
        if(err){
            return next(err);
        }
        res.status(201);
        res.json(user);
    });
}

The problem is:

The response is always "User already exists!" with status code - 400

I want to display the message only if user exists (ie if given credentials matches) else respond with 201

Upvotes: 0

Views: 1855

Answers (2)

Siddhartha Chowdhury
Siddhartha Chowdhury

Reputation: 2732

Okay guys I figured out a solution, i will put it here in case if it helps someone

if (user) { // will be true even if user = [] 
   res.status(400);
   return res.json('User already exists!');
}

In case when user is not found in the DB , user is = [ ] , this means [ ] != false , hence the message within the scope is getting displayed.

Upvotes: 0

war1oc
war1oc

Reputation: 2755

register:function(req, res, next){
    var params = req.params.all();

    User.find({
        or : [
            { usrnm:params.usrname },
            { eml:params.eml }
        ]
    })
    .exec(function (err, users){
        if (err) {
            return res.negotiate(err);
        }
        if (users.length) {
            res.status(400);
            return res.json('User already exists!');
        } else {
             User.create(params, function(err, user){
              if(err){
                return next(err);
              } else {
                res.status(201);
                res.json(user);
              }
           });
        }
    });
}

You should call the create user method if a user with those parameters do not already exist, and so should put it inside the callback.

The User.find() function returns an array, so you need to check its length to see if there are any matching objects.

Upvotes: 3

Related Questions