Mongoose schema optional fields

冷暖自知 提交于 2020-01-01 01:12:09

问题


I have a user schema with mongoose in nodejs like this

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?


回答1:


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

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

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




回答2:


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

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
});


来源:https://stackoverflow.com/questions/24942037/mongoose-schema-optional-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!