NoSQL brought flexibility to the tabular world of databases. MongoDB in particular became an excellent option to store unstructured JSON documents. Data starts as JSON in the UI and undergoes very few transformations to be stored, so we get benefits from increased performance and decreased processing time.

But NoSQL does not mean a complete lack of structure. We still need to validate and cast our data before storing it, and we still may need to apply some business logic to it. That is the place Mongoose fills.

In this article we’ll learn through an example application how we can use Mongoose to model our data and validate it before storing it to MongoDB.

We will write the model for a Genealogy app, a Person with a few personal properties, including who their parents are. We’ll also see how we can use this model to create and modify Persons and save them to MongoDB.

What is Mongoose?

How MongoDB Works

To understand what is Mongoose we first need to understand in general terms how MongoDB works. The basic unit of data we can save in MongoDB is a Document. Although stored as binary, when we query a database we obtain its representation as a JSON object.

Related documents can be stored in collections, similar to tables in relational databases. This is where the analogy ends though, because we define what to consider “related documents”.

MongoDB won’t enforce a structure on the documents. For example, we could save this document to the Person collection:

  "name": "Alice"

And then in the same collection, we could save a seemingly unrelated document with no shared properties or structure:

  "latitude": 53.3498,
  "longitude": 6.2603

Here lies the novelty of NoSQL databases. We create meaning for our data and store it the way we consider best. The database won’t impose any limitation.

Mongoose Purpose

Although MongoDB won’t impose an structure, applications usually manage data with one. We receive data and need to validate it to ensure what we received is what we need. We may also need to process the data in some way before saving it. This is where Mongoose kicks in.

Mongoose is an NPM package for NodeJS applications. It allows to define schemas for our data to fit into, while also abstracting the access to MongoDB. This way we can ensure all saved documents share a structure and contain required properties.

Let’s now see how to define a schema.

#javascript #node #database #mongo #mongoose

Mongoose with Node.js - Object Data Modeling
1.40 GEEK