Richard G
Richard G

Reputation: 5683

What is the right syntax to make required field depend on another field/function in Mongoose

I'm trying to make fields required depending on value in current Mongoose object. How can I make customerInfo required depend on the value in status in below?

this reference is not working in that function.

Ideally would prefer to declare the function outside the schema definition too but couldn't get it to work. I also couldn't find the documentation on the feature to make required support a function, but I'm fairly sure it's supported...

var OrderSchema = new Schema(
{

    status: {
      type: String,
      trim: true,
      enum: refdata.orderStatus,
      default: refdata.orderStatus[0]
    },

    createDate: {
      type: Date,
      default: Date.now
    },
    customerInfo: {
      type: OrderCustomer,
      required: function (v){
        return this.status === 'INIT';
      }
    } 
}

Upvotes: 1

Views: 522

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

you can achieve what you want using pre middleware.

For more information on pre, see Mongoose middleware documentation

use pre while saving and apply your logic to check if a particular field is required or not. Based on your logic implemented in pre('save'), If it is required or not required, you can flag an error in either case.

Try something like this:

var OrderSchema = new Schema(..);
OrderSchema.pre('save', function(next) {
  // check if it is required or not
  if(this.status == "INIT")
  {
    //customerInfo Required
    //check if customerInfo is present or not.
    // Flag issue if not present.
    var err = new Error('customerInfo required');
    next(err);
  }
  next();
});

Upvotes: 1

Related Questions