如何在mongodb中设置整数的默认值? [英] How do I set default value of an integer in mongodb?
问题描述
我是mongodb和node.js的新手.让我知道,创建用户后如何设置默认值.
I'm new to mongodb and node.js. Let me know, how do I set default value after creating the user.
这是我当前的代码:
// 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);
});
});
我希望在创建用户后将我的赢,输,平局字段设置为0.在我的用户架构中,它们被声明为数字".
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'.
推荐答案
在使用Mongoose时,您可以将默认值设置为Schema
定义的一部分:
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 }
});
在此处中记录了这些选项.如果将默认值设置为一个函数,它将在实例化Model时执行,这也很酷.例如,如果它是:default: Date.now
,则在创建模型时将调用Date.now()
函数.
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.
这篇关于如何在mongodb中设置整数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!