Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Model Custom Error Message for Enums

I would like to customize the validation messages that my Mongoose Models produce.

I tend to NOT put my validations (e.g. required) on the schema object directly because there is no freedom to have custom error messages. e.g.

sourceAccountId: {
  type: Schema.ObjectId,
  require: true,
  ref: 'Account'
}

instead I do the following.

sourceAccountId: {
  type: Schema.ObjectId,
  ref: 'Account'
}

ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');

I have been unable to find a way to override the default enum message when a field has enum constraints.

My Model is Listed Below, with the status validation message working fine for required, but not for enum.

'use strict';

var _ = require('lodash');

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var ConnectionRequestSchema = new Schema({
  created_at: { type: Date },
  updated_at: { type: Date },

  sourceAccountId: {
    type: Schema.ObjectId,
    ref: 'Account'
  },

  status: {
    type: String,
    enum: ['pending', 'accept', 'decline'],
    trim: true
  }
});

// ------------------------------------------------------------
// Validations
// ------------------------------------------------------------

ConnectionRequestSchema.path('sourceAccountId').required(true, 'Source Account is required.');
ConnectionRequestSchema.path('status').required(true, 'Status is required.');
//ConnectionRequestSchema.path('status').enum(['pending', 'accept', 'decline'], 'Status is invalid, valid values include [pending, accept, decline]');

// ------------------------------------------------------------
// Save
// ------------------------------------------------------------

ConnectionRequestSchema.pre('save', function (next) {
  var now = new Date().getTime();

  this.updated_at = now;
  if (!this.created_at) {
    this.created_at = now;
  }

  next();
});

module.exports = mongoose.model('ConnectionRequest', ConnectionRequestSchema);
like image 600
David Cruwys Avatar asked May 24 '16 03:05

David Cruwys


1 Answers

Try something like it:

var enu = {
  values: ['pending', 'accept', 'decline']
, message: 'Status is required.'
}


var ConnectionRequestSchema = new Schema({
  ...

  status: {
    type: String
  , enum: enu
  , trim: true
  }
});
like image 128
andergtk Avatar answered Oct 22 '22 20:10

andergtk