Learning Node.js — Part 6

Validating Data in MongoDB

Osha Groetz
2 min readApr 27, 2021
Great Article on Data Validation & Image credit: Sharjeel Ashraf

“In computer science, data validation is the process of ensuring data has undergone data cleansing to ensure they have, that is, that they are both correct and useful. It uses routines, often called “validation rules”, “validation constraints”, or “check routines”, that check for correctness, meaningfulness, and security of data that are input to the system. The rules may be implemented through the automated facilities of a data dictionary, or by the inclusion of explicit application program validation logic of the computer and its application.”²

Validating Presence Of

On line 8, we are requiring the presence of a value for the attribute “name” when creating a new instance of Musician. If we comment out name (line 20), and run this code (node index.js), we will see the following error:

This validation is only meaningful in Mongoose, not MongoDB. Use both Mongoose and Joi for data validation.

Mongoose Built-In Validators

Validators specific to Strings:

  • minlength → specify value
  • maxlength → specify value
  • match →
  • enum → an array of valid strings

For Numbers, validations include:

  • min
  • max
Built-In Validators

Mongoose Custom Validators

The custom validations that we can write in Mongoose can include the properties of validator (function) and message (to display in the case our validation fails). Lines 23–28:

Async Validators in Mongoose

Mongoose Validation Errors

To iteerate over and read each invalid property of errors object:

Console will resemble something like this:

A Few More Validations on SchemaType Objects:

Strings:

  • lowercase → convert value automatically to lowercase
  • uppercase → convert value automatically to uppercase
  • trim → auto remove any paddings around string

Numbers:

  • get → useful for any data that may have been added before validations set. Getters let you transform data in MongoDB into a more user friendly form³
  • set → Setters let you transform user data before it gets to MongoDB³

If you would like to view my full application to date (example uses different models), which includes not only some of the validations above, but also how to refactor our routes (from Part 3) to implement async functions, that code can be found in my github repo here.

  1. Node.js Tutorial for Beginners | Programming with Mosh | “https://www.youtube.com/watch?v=TlB_eWDSMt4&t=2349s”\
  2. Data Validation | “https://en.wikipedia.org/wiki/Data_validation
  3. Getters/Setters in Mongoose | “https://mongoosejs.com/docs/tutorials/getters-setters.html

--

--

Osha Groetz
Osha Groetz

Written by Osha Groetz

Software Engineer. React, Javascript, Typescript, HTML, CSS, Ruby, Ruby On Rails

No responses yet