node.js 如何在 mongodb 中设置整数的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18934493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:42:51  来源:igfitidea点击:

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

node.jsmongodb

提问by cor03rock

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

我是 mongodb 和 node.js 的新手。让我知道,如何在创建用户后设置默认值。

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'.

我希望在创建用户后我的赢、输、平局字段设置为 0。在我的用户架构中,它们被声明为“数字”。

回答by WiredPrairie

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

当您使用 Mongoose 时,您可以将默认值设置为Schema定义的一部分:

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.

这些选项记录在此处。如果您将默认值设置为函数,它将在实例化模型时执行,这也很酷。例如,如果它是:default: Date.now,它将Date.now()在创建模型时调用该函数。