node.js Mongoose 模式可选字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24942037/
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 17:41:55  来源:igfitidea点击:

Mongoose schema optional fields

node.jsmongodbmongooseschema

提问by HarveyBrCo

I have a user schema with mongoose in nodejs like this

我在 nodejs 中有一个带有 mongoose 的用户架构,就像这样

userschema = mongoose.Schema({
    org: String,
    username: String,
    fullname: String,
    password: String,
    email: String
});

Except sometimes I need to add some more fields.

除了有时我需要添加更多字段。

The main question is: Can I have optional fields in a monogoose schema?

主要问题是:我可以在monogoose 模式中有可选字段吗?

回答by Talha Awan

In addition to optional(default) and required, a field can also be conditionally required, based on one or more of the other fields.

除了optional(默认)和required 之外,还可以根据一个或多个其他字段有条件地要求字段。

For example, require password only if email exists:

例如,仅当电子邮件存在时才需要密码:

var userschema = mongoose.Schema({
    org: String,
    username: String,
    fullname: String,
    password: {
        type: String,
        required: function(){
            return this.email? true : false 
        }
    },
    email: String
});

回答by JohnnyHK

All fields in a mongoose schema are optional by default (besides _id, of course).

默认情况下_id,猫鼬模式中的所有字段都是可选的(当然,除了)。

A field is only required if you add required: trueto its definition.

仅当您添加required: true到其定义时才需要该字段。

So define your schema as the superset of all possible fields, adding required: trueto the fields that are required.

因此,将您的架构定义为所有可能字段的超集,添加required: true到所需的字段中。