Home > database >  Reference field from within the same schema
Reference field from within the same schema

Time:06-02

I have a schema

const mySchema = new Schema({
  limit: Number,
  currentlyAdded: Number
});

I want currentlyAdded to be at most limit.
max doesn't seem to accept a function so I can't do function() { return this.limit }

Is there a way to somehow reference limit field from currentlyAdded so I could do something like that

const mySchema = new Schema({
  limit: Number,
  currentlyAdded: {
    type: Number,
    max: %reference_to_limit%
  }
});

CodePudding user response:

You can use validate property to validate the limit condition by calling a function,

const mySchema = new Schema({
  limit: Number,
  currentlyAdded: { 
    type: Number,
    validate: [checkLimit, "Exceeded the limit!"]
  }
});

// CHECK VALIDATION
function checkLimit(currentlyAdded) {
  return currentlyAdded <= this.limit;
}
  • Related