1

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?

Community
  • 1
  • 1
Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
  • Can you just use "email" as the `_id` value? Would seem a bit silly if sails will not let you use your own primary key choice. –  Jun 14 '15 at 09:22
  • 2
    It also seems you did not read the issue report fully. There is an explanation about what is wrong here: http://stackoverflow.com/questions/25382296/sailsjs-and-mongo-unique-attribute-is-ignored –  Jun 14 '15 at 09:29

1 Answers1

2

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

Juraj Petrik
  • 895
  • 1
  • 10
  • 25
  • Well maybe part of what needs to be done to fix the issued code. But really there is nothing wrong with using "unique" indexes, which the OP thinks they cannot do, but is clearly not the case. So there should be no need to code to "work around" this. That would be the better advice I think. –  Jun 14 '15 at 09:31