Peter Warbo
Peter Warbo

Reputation: 11710

MongooseJS clean string before doing any validations

I need to clean a string in MongooseJS before doing any type of validation. How can I access a field of my model and alter (clean) the field and only then do the validation of the field?

For instance this is what my model looks like:

var NotificationSchema = new Schema({
    topic: { type: String, required: true }
});

I want to clean topic (remove any whitespace characters from it). After that has been done I want to check that topic is minimum 2 characters and maximum 60 characters.

Simply put, I want the topic to be cleaned first thing.

Upvotes: 0

Views: 224

Answers (1)

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

If you just want to validate against the transformed data you can use custom validation. http://mongoosejs.com/docs/validation.html

var NotificationSchema = new Schema({
    topic: { type: String, required: true }
});

NotificationSchema.schema.path('topic').validate(function (value) {
  value = value.replace(/\s/g, '');
  if (value.length > 1 && value.length < 61)
    return true;
  return false;
}, 'Invalid length');

If you want to also save the transformed data you would use the pre save hook to do the transform. You will still need to do custom validation as Mongoose doesn't have built in support for string length. See here for middleware docs: http://mongoosejs.com/docs/middleware.html

var NotificationSchema = new Schema({
    topic: { type: String, required: true }
});

NotificationSchema.pre('validate', function(next) {
  this.topic = this.topic.replace(/\s/g, '');
  next();
});

NotificationSchema.schema.path('topic').validate(function (value) {
  if (value.length > 1 && value.length < 61)
    return true;
  return false;
}, 'Invalid length');

Upvotes: 1

Related Questions