Mongoose schema optional fields

HarveyBrCo picture HarveyBrCo · Jul 24, 2014 · Viewed 24.7k times · Source

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?

Answer

Talha Awan picture Talha Awan · Jun 3, 2017

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