Building Apps with Mongo(ose)


Today's DB Objectives:


Some duplication

Last time we ran out of time without making it all the way through the notes. Today I'm going to duplicate some of the notes from last time and add some fresh material to round it out. My goal is that you leave able to create a Node-based API backed by Mongo.

A completely generic API

For this mini-project we'll build a backend that will just work for almost any front-end you want to build. It won't do much, but if you are a front-end developer that wants to work fast this will do your job. Visit the repo on GitHub and follow the intstructions in the README.md.

The Schema API

In the above examples we didn't really lean on any structure, just loosey-goosey CRUD. Now I want to introduce a little bit more software engineering into your Mongo work. By using Mongoose we get the ability to use Schemas (still flexible but structured). The ethos is that Schemas are converted to Models which instantiate to Documents. When we work with models it becomes Object-Oriented coding.

Let's play with some Schema features:

MiniTask 1: Create a Dog Schema, with some pertinent characteristics

MiniTask 2: Give each dog the ability to bark their name.

MiniTask 3: Make a Class-level method for listing the names of all dogs.

I'll talk about arrays in Schema a little further down.

Check out the mongoose guide.

A Reddit Clone

Next I want to show you a pretty functional MEAN stack built on this tech. The github code is here and it should run on your cloud9 environment with a quick npm insall. Again we will talk this out in class and make some alterations.

Sample reddit

Task 1: get this running.

Task 2: create some posts in the database directly then refresh your page.

Task 3: create some comments in the database directly.

Task 4: Talk out how you would keep someone from upvoting more than once.

The JOIN problem

The biggest complaint about noSQL is living without JOINs. That is because we want to think in terms of relationships. In particular many to 1, 1 to many, 1 to 1, and many to many. In Mongo we can solve this problem in several ways.

Each document has an _id and documents can store other documents or arrays. So you can choose:

Mongoose has a great feature called populate which will "re-hydrate" these references when you need them.

Here is a sample stolen from them:

Last Task: Create a blog engine which has comments and authors. Reference between them in two different ways from the above list.