MongoDB + Mongoose

Refactoring code is never exciting but it does teach you a lot about the strengths/weaknesses of one library/database/ORM to another. Today we are refactoring our code from BookshelfJS/MySQL to MongoDB and it's not too bad.

Previously, we were using SQL and it required us to predefine our schema beforehand. This was a ton of work---to query data, you have to add/remove attributes from the schema, define relationships (how data is connected), and join data.

From what I understand, this is particularly hard with Node.js, where you have to basically create your own relational database management system (RDBMS). So we used Bookshelf and Knex, two ORMs that help you work with the data.

MongoDB seems to just change this whole way of thinking away from RDBMS towards...well, MongoDB. There are so many things that you don't need to do---Mongo just does it all for you.

The link I provided below gives a great overview on the difference--but the TLDR:

The immediate and fundamental difference between MongoDB and an RDBMS is the underlying data model. A relational database structures data into tables and rows, while MongoDB structures data into collections of JSON documents.

I can see why Mongo is the main database of choice for working with Node. Using Mongoose, the object modeling tool for MongoDB and Node, you just define your data model in your code. There's no need to make another file.

No need for our schema in the database! No need to map it into project objects and classes! This isn't a bad start for MongoDB ingratiating itself into my coding life.

There are only two aspects of Mongoose to take note of: Schemas and Models.

Schemas are super easy in Mongoose. If we were making a schema for a list of students, it would probably look something like this:

var studentsSchema = new mongoose.Schema({
	firstname: String,
    lastname: String,
    school: String,
    grade: Number
})

That establishes the bare-bones to what information you want to track for students.

To create a model, which is a compiled version of a schema, you only need to write one line:

var Student = mongoose.model('Student', studentsSchema);

It is the model that handles the reading, creating, updating and deleting of documents/entries in our database.

So much easier!

Resources:
Transitioning from Relational Databases to MongoDB from the MongoDB blog
MongoDB docs, of course