vineet sah vineet sah - 19 days ago 5
Node.js Question

How to make optional field in Mongoose?

I want to make optional field in Mongoose schema.

Here is my

Log
schema.

var logSchema = new Schema({
logType: {
type: String,
enum: ['user', 'lead', 'knowledgecenter'],
required: true
},
userLog: {
name: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
required: true
}
},
leadLog: {
title: {
type: String,
required: true
},
leadId: {
type: Schema.Types.ObjectId,
required: true
}
}
});


I want to insert document in above
Log
schema either with
{logType:'user',userLog:{userId:'5fcJFjslkka4lsdk'}}
or
{logType:'lead',leadLog:{leadId:'5fcJFjslkka4lsdk'}}
.

But at this moment mongoose throw
ValidatorError: Path required
error.

Answer

Instead of setting required to true you can set it to be a function that returns true only in the case where it is required.

this should do the trick:

var logSchema = new Schema({
    logType: {
        type: String,
        enum: ['user', 'lead', 'knowledgecenter'],
        required: true
    },
    userLog: {
        name: {
          type: String,
          required: function() { return this.logType === 'user'; }
        },
        userId: {
          type: Schema.Types.ObjectId,
          required: function() { return this.logType === 'user'; }
        }
    },
    leadLog: {
      title: {
        type: String,
        required: function() { return this.logType === 'lead'; }
      },
      leadId: {
        type: Schema.Types.ObjectId,
        required: function() { return this.logType === 'lead'; }
      }
    }
});