Check for existing user doesn't go along

65 Views Asked by At

As the Waterline's unique attribute is ignored for MongoDB, I take up the decision to make a check for existing model entry in my code:

    var username = req.param('username');
    var email = req.param('email');
    var asd = "";
        // Do check if user already exists
        User.findOne({username: username}, function (err, user) {
            asd = "invalid USERNAME";
            console.log(asd);
            if(err){
                return res.serverError('error creating user' + err);
            }
            if(user){
                asd = "invalid USERNAME";
                console.log(asd);
                return res.json({status: "INVALID_USERNAME"});
            }
        });
        User.findOne({email: email}, function (err, user) {
            asd = "invalid EMAIL";
            console.log(asd);
            if(err){
                return res.serverError('error creating user' + err);
            }
            if(user){
                asd = "invalid EMAIL";
                console.log(asd);
                res.json({status: "INVALID_EMAIL"});
            }
        });

        // Create the user
        User.create({.....});

Nevertheless, I never get in the findOne methods, even though the user with the provided credentials does exist in the database. I tried debugging, and I don't get in the statement. I even put this asd variable, just to check if smth happens, but unsuccessfully. And the user keeps being created again and again, with the same credentials.

Any thoughts on what am I missing?

1

There are 1 best solutions below

1
On BEST ANSWER

You need to put the create inside the callback

User.findOne(...).exec(
   function(err,user){
      if(!user) User.create(...)
});

But as others have commented there might not be a need for this workaround. In the issue you linked, they explain the it only happens with

migrate: safe

set either config/models.js or chosen in the command line interface. So just set it to something else. It is enough to set it once, run sails lift, and change it back to safe if you prefer