These are chat archives for Automattic/mongoose

1st
Apr 2018
ParanoidAditya
@ParanoidAditya
Apr 01 2018 09:21
Hi guys,
How do I prevent saving of a duplicate username per say?
function checkUserExists(user) { Users.findOne({ username: user }, function (err, user) { if (err) { console.log("Error connecting"); } else if (user==null){ return false; } else{ return true; } }); };
Kev
@lineus
Apr 01 2018 09:25

@ParanoidAditya you can add the unique property to the path in your schema definition

const userSchema = new Schema({
  username: {
    type: String,
    unique: true
  }
})

this will create a unique index on the collection in mongodb.

ParanoidAditya
@ParanoidAditya
Apr 01 2018 09:28
@lineus so it'll throw an error while saving?
Kev
@lineus
Apr 01 2018 09:29
once the index is created on the collection, yes.
this index will be created on the first save, so as long as you're not initially saving duplicated usernames, it will work as you expect.
ParanoidAditya
@ParanoidAditya
Apr 01 2018 09:31
@lineus That was easier than anticipated
thanks
Kev
@lineus
Apr 01 2018 09:32
anytime
ParanoidAditya
@ParanoidAditya
Apr 01 2018 09:33
var code = "formatted";
var userSchema = new Schema({
      name: {
        type: String,
        validate: {
          validator: function(v, cb) {
            User.find({name: v}, function(err,docs){
               cb(docs.length == 0);
            });
          },
          message: 'User already exists!'
        }
      }
    });
I saw this on stackoverflow
could not wrap my head around it
correct me if I am wrong, you pass it a callback fn?
Kev
@lineus
Apr 01 2018 09:35
that will result in wasted network traffic and resources on both sides of the wire. You can just try the save and handle the error.
pass what a callback function? the save?
ParanoidAditya
@ParanoidAditya
Apr 01 2018 09:53
The solution you gave me works fine, I will look this one up later
Thanks again for the help
Kev
@lineus
Apr 01 2018 10:06
@ParanoidAditya your question made me question whether there was a node built-in to ask a user for input ( I'm pretty new to js and node still) and there is, so I wrote a contrived script for fun that is sort of relevant to your question: here is a gist
so thank you!
ParanoidAditya
@ParanoidAditya
Apr 01 2018 10:10
I am pretty new myself, I am enrolled in the mongodb for Node.js class they have and have been just playing around with things
ParanoidAditya
@ParanoidAditya
Apr 01 2018 13:10
router.post('/changeUserPermissions', function (req, res, next){
    console.log(req.body.username);
    console.log(req.body.canPost);
    if (req.session.userName === "admin" ) {
        if(req.body.canPost){
            Users.findOneAndUpdate({"username":req.body.username}, {$set:{"canPost":false}}, function(err, doc){
                if (err){
                    res.render('listUsers', {errmessage:err});
                }
                else {
                    res.redirect(302,'/admin/listUsers');
                }
            });
        }
        else{
            Users.findOneAndUpdate({"username":req.body.username}, {$set:{"canPost":true}}, function(err, doc){
                if (err){
                    res.render('listUsers', {errmessage:err});
                }
                else {
                    res.redirect(302,'/admin/listUsers');
                }
            });
        }  
    }
    else if (req.session.userName == null) {
        res.render('logonSplash', { title: 'Not Twitter - Login', message: "You must be logged in to add users" });
    }
    else {
        res.render('/home', { title: 'unauthorized', errmessage: "Unauthorized" });
    }
});
If the state is true in the db it will toggle it to false but it does not toggle it back to true
does not even connect to the DB
Kev
@lineus
Apr 01 2018 13:16
how are you sure it isn't connecting to the db? are you using mongoose.set('debug', true) ?
ParanoidAditya
@ParanoidAditya
Apr 01 2018 13:16
No I was just looking at the db console for connections reqs
I will try mongoose.set('debug', true)
Kev
@lineus
Apr 01 2018 13:17
are you meeting the conditions to get to one of the find* operations?
and did you remember to connect to the db with mongoose.connect(url, options)?
by default Model will queue up your operations until you connect
ParanoidAditya
@ParanoidAditya
Apr 01 2018 13:18
I am just using mongoose.connect(url)
no options
Kev
@lineus
Apr 01 2018 13:20
yeah, mongoose debug will show you any queries it runs. are you watching the same db your app is pointed at?
just trying to think of things I've done in the past :)
ParanoidAditya
@ParanoidAditya
Apr 01 2018 13:21
Yes watching the same db
Kev
@lineus
Apr 01 2018 13:23
is your query callback redirecting you successfully to /admin/listUsers ?
ParanoidAditya
@ParanoidAditya
Apr 01 2018 13:23
yes it is
and debug showed the first if statement is running all the time
okay a req.body.canPost==="true" fixed it
i did try == before but it did not work
Kev
@lineus
Apr 01 2018 13:37

@ParanoidAditya coercion is tricky sometimes.
for example:

get-issue>: node
> x = 'false'
'false'
> if (x) { console.log('truthy') }                   // not coerced just a truthy string
truthy
undefined
> if (x == true) { console.log('truthy') }    // coercion and booleans don't mix well
undefined
> if (x == false) { console.log('truthy') }   // coercion and booleans don't mix well
undefined
>

checkout @getify's series 'You dont know JS' this section on coercion is relevant to this for sure.