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?
It seems that the default value of the required attributes of each field in mongoose schema is false.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
The $set operator replaces the value of a field with the specified value.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With