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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With