Search code examples
node.jsmongodbvalidationmongoosemongoose-plugins

Is it possible to use `required: true` validation by clause?


I have the following schema:

var Schema = new mongoose.Schema({});

Schema.add({
    type: {
       type: String
       , enum: ['one', 'two', 'three']
    }
});

Schema.add({
    title: {
       type: String
       //, required: true ned set by some conditional
    }
});

As you can from the preseding schema definition I have two field type and title. The second one (title) have to be required: true only if type is (one | two) and have to be false if type is three.

How could I do it with mongoose?

EDIT: thanks for the answers. I have one more related question that I ask here:

I it possible to remove field if that not required? Let's say the type if three but also been provided title field also. To prevent storing of unnecessary title in this case how to remove it?


Solution

  • You can assign a function to the required validator in mongoose.

    Schema.add({
      title: String,
      required: function(value) {
        return ['one', 'two'].indexOf(this.type) >= 0;
      }
    });
    

    The documentation doesn't explicity state that you can use a function as an argument but if you click show code you will see why this is possible.