backend,  Programming

Adding custom validators in MongoDB+Mongoose

Today we’re going to add custom validators to some of our documents in Mongoose.

Things you’ll have to be familiar with for this article

  • MongoDB
  • Mongoose
  • Nodejs

Why make custom validators?

When dealing with data sent over the web we often find that the inputs we are given tend to be suboptimal. We need some way of relaying to our end users that they’re not meeting our input needs. This is where validators come in. We can define a function that will arbitrate what is and isn’t an acceptable input for a given field. To get started properly let’s define a model and give it a few fields.

const Mongoose = require('mongoose');
Mongoose.connect('mongodb://127.0.0.1/SomeDB',
{
  useNewUrlParser: true,//to get rid of annoying 
  useUnifiedTopology: true,//warning messages

});
//Now that we're connected let's make a user schema


const Schema = mongoose.Schema;
const HorseSchema = new Schema
({
  name:{type: String, required:true},
  color: 
  { 
    type: String, 
    required: true
  },
  bad:{type: Boolean, default: false},
   

});
Mongoose.model('user',UserSchema);//and model that bad boy in our DB

Now that we’ve laid out our schema we can add some validators. In this instance, we really don’t want folks to give us “green”, “magenta” or “rainbow” horses. To prevent this, we’ll implement a simple validator object that will check if our document’s color is a fit and if it does not contain our desired color it will complain with a provided reason.

ColorValidator =
{
  validator: function(documentColor) 
  {
    colors = ['red','brown','yellow','white','black']
    return colors.includes(documentColor);
  },
  message: 'Please select a valid color',
  reason: 'A non-normal color was provided'
}

const HorseSchema = new Schema
({
  name:{type: String, required:true},
  color: 
  { 
    type: String, 
    required: true,
    validate: ColorValidator
  },
  bad:{type: Boolean, default: false},
});

Mongoose.model('user',UserSchema);//and model that bad boy in our DB


That wraps up our tutorial. If you’re interested in extending this code yourself and implementing it in your own project, simply adapt the “validator” part of the ColorValidator object and shoehorn it into your own work.

Abe is a full-stack MEVN developer, who enjoys classical fencing with French Foil and German longsword. His interests also include photography, boxing, and Scotch whisky.

Leave a Reply

Your email address will not be published. Required fields are marked *