问题
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