0

I'm using the sails-mongo adapter to connect to my local mongodb server. I have one model, that is Users.js and I'm trying to find the user with a specific ID.

User.findOne({userID:authID}).exec(function(error, found){
            console.log(typeof found);
            console.log(found);
            if (typeof myObj !== "undefined") {
                console.log('user already exists');
                //res.send({response: 'userExists'});
            } else {
                console.log('gotta create a new user');
                User.create({
                userID: authID, 
                name: 'name',
                age: 'age', 
                gender: 'gender',
                loggedIn: true}).exec(function(err, created) {
                    if (err) 
                        console.log(err);
                    else {
                        console.log(typeof created);
                        console.log(created.keys({}).length);
                        console.log('user created: ' + created.name);
                    }
                });

                //res.send({response: 'userCreated'});
            }

        });

The above code gives me some errors on the console log

errors when I run sails lift

Rockstar5645
  • 4,376
  • 8
  • 37
  • 62
  • A couple of things: Your code doesn't handle the `err` object. `.find()` always returns an array of objects. Checking `user.length` should work, or if `user` is undefined, user.length will throw a `TypeError`. What do you get if you run `User.find({userID:authID}).exec(function(e,r){console.log(e||r})`in sails console? –  Dec 18 '15 at 03:38
  • `console.log(r)` returns an empty array `[]` and `console.log(e)` returns `null`, but that doesn't make any sense, the record already exists in the database, it should be able to find it. – Rockstar5645 Dec 18 '15 at 05:20
  • How do you know it's creating a new user? Your code does not pass a callback function to `User.create()`, nor does it invoke `.exec()` on `User.create()`. Regardless of what happens when you invoke `.create()` as in your code above, it will always send your positive response, even if it doesn't create the user. –  Dec 18 '15 at 05:26
  • @metzuda I edited my query, I commented everything between the else statement so I got `undefined` twice in the console log (for the two console logs in the if statement) but when I uncomment the statements between else, I get new errors, something to do with my node modules. – Rockstar5645 Dec 18 '15 at 06:09
  • Looks like a validation error. Do you have `require:true` instead of `required:true` in your model? –  Dec 18 '15 at 07:25
  • @metzuda HOW WERE YOU ABLE TO TELL?!?!?!?!?!?!?! thank you so much!!! – Rockstar5645 Dec 18 '15 at 07:34
  • No problem! Glad to help. –  Dec 18 '15 at 07:35

0 Answers0