Mongoose conditional required validation Mongoose conditional required validation mongoose mongoose

Mongoose conditional required validation


As of mongoose 3.9.1, you can pass a function to the required parameter in the schema definition. That resolves this problem.

See also the conversation at mongoose: https://github.com/Automattic/mongoose/issues/941


For whatever reason, the Mongoose designers decided that custom validations should not be considered if the value for a field is null, making conditional required validations inconvenient. The easiest way I found to get around this was to use a highly unique default value that I consider to be "like null".

var LIKE_NULL = '13d2aeca-54e8-4d37-9127-6459331ed76d';var conditionalRequire = {  validator: function (value) {    return this.type === 'other' && val === LIKE_NULL;  },  msg: 'Some message',};var Model = mongoose.Schema({  type: { type: String },  someField: { type: String, default: LIKE_NULL, validate: conditionalRequire },});// Under no condition should the "like null" value actually get persistedModel.pre("save", function (next) {  if (this.someField == LIKE_NULL) this.someField = null;  next()});

A complete hack, but it has worked for me so far.


Try adding this validation to the type attribute, then adjust your validation accordingly. E.g.:

function validator(val) {  val === 'other' && this.thing === '';}