0

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?

Erik
  • 14,060
  • 49
  • 132
  • 218

3 Answers3

2

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.

zmln
  • 56
  • 4
1

An alternative to the accepted answer using the validate option:

Schema.add({
  title: String,
  validate: [function(value) {
    // `this` is the mongoose document
    return ['one', 'two'].indexOf(this.type) >= 0;
  }, '{PATH} is required if type is either "one" or "two"']
});

UPDATE: I should have noted validators are only run if a field is not undefined with the only exception being required. So, this wouldn't be a good alternative.

Jason Cust
  • 10,743
  • 2
  • 33
  • 45
0

you could try one of the following:

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

Schema.title.required = true;

or

var sky = 'gray'

var titleRequired = sky === 'blue' ? true : false

Schema.add({
    title: {
       type: String,
       required: titleRequired
    }
});
ReDEyeS
  • 851
  • 5
  • 16
  • I need to get this case on creating new document: `new schemaModel({type: "one", "title": undefined})`; – Erik Apr 02 '15 at 14:51