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);
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With