Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set default value of an integer in mongodb?

I'm new to mongodb and node.js. Let me know, how do I set default value after creating the user.

Here is my current code:

// CREATE USER
app.post("/user/create", function (req, res) {
    var user = new User({
        username: req.body.username,
        password: req.body.password,
        email: req.body.email,
        //changes made
        win: req.body.win,
        lose: req.body.lose,
        draw: req.body.draw
    });
    user.save(function (err, user) {
        if (err)
            res.json(err)
        //res.end('Registration '+user.username +' Ok!');
        req.session.loggedIn = true;
        res.redirect('/user/' + user.username);
    });
});

I want that my win, lose, draw fields are set to 0 after creating a user. In my user schema they are declared as 'Numbers'.

like image 804
cor03rock Avatar asked Sep 21 '13 15:09

cor03rock


1 Answers

As you're using Mongoose, you can set the default as part of the Schema definition:

var userSchema = new Schema({ 
    win: { type: Number, default: 0 }
});

The options are documented here. It's also cool that if you set the default to a function, it will execute when the Model is instantiated. For example, if it were: default: Date.now, it will call the Date.now() function when a model is created.

like image 104
WiredPrairie Avatar answered Oct 26 '22 04:10

WiredPrairie