Install Simple Schema for Collection Validation

Learn about database schemas and their use.

We'll cover the following

Database schema

A database schema is a blueprint that enforces the uniformity of the data stored. MongoDB doesn’t require that the stored data is uniform. We can arbitrarily store any value in a collection. JavaScript objects don’t have a strict type system or structure. So, to ensure that we don’t mess things up by storing heterogeneous JavaScript objects in the MongoDB collection, we’ll use an object schema validator.

We can install a package that enforces data uniformity against a schema. The npm package called simpl-schema validates JavaScript objects, ensuring that they match a schema. This package is installed through the terminal to our application by running the following:

meteor npm install simpl-schema
meteor add aldeed:collection2

The simpl-schema package allows a schema to be used to enforce data uniformity in the database. The second package installed, the aldeed:collection2, is a package that extends the Mongo collection so that a schema can be attached to it.

Opening the imports/api/authors/authors.js file on the widget below should reveal SimpleSchema, which was imported on line 2. On lines 6–16 the insert, update, and remove operations of MongoDB are denied and not allowed from the client. This is done for data security reasons because client data can’t be trusted and must be validated at the server. The way to perform CRUD (create, read, update, and delete) operations is through Meteor Methods on the server.

On line 18, we create the AuthorsSchema, which is the blueprint for the authors collection. The schema specifies that an author record must contain a firstname, surname, contactNumber and optional fields like email and address. After creating the schema, it’s attached to the AuthorCollection, which means that inserting new data into the collection validates against the AuthorsSchema.

Get hands-on with 1200+ tech skills courses.