Deep Dive Into Node.js and MongoDB - Day 6


In case you missed the other days:
Day 1 Deep Dive
Day 2 Deep Dive with MongoDB
Day 3 Deep Dive with MongoDB
Day 4 Deep Dive with MongoDB
Day 5 Deep Dive with MongoDB

Today's posting is a intro for myself into mongoose, a popular object modeler for node.js. This continues my deep dive into learning the node.js equivalents to what I used to in the ASP.NET world, for this post in particular in how mongoose compares to Entity Framework.


As mentioned previously, this point I am going to assume MongoDB is up and running, if you do not, check my first day post for details on how to get it up and running.

Utilizing Mongoose and cleaning up the MongoDB code

As I mentioned in yesterday's post I wanted to clean up the code further in particular all of the MongoDB code. Knowing Mongoose would help in this regard I replaced the MongoDB code I had with interestingly enough less code and an object model for my "Posts" object. The process was fairly similar to a code first approach with Entity Framework so very comfortable.

Migrating all of my MongoDB code was extremely painless, even adding in the model creation code left it with just the following:

var mongoose = require('mongoose');


var postSchema = new mongoose.Schema({ id: Number, likes: Number });

var Post = mongoose.model('Post', postSchema);

module.exports = Post;
What is neat is the actual usage of the Post object. In my routes.js file:

var express = require('express');
var Post = require('./dbFactory');

var router = express.Router();

router.get('/api/Test', function (request, response) {
    var argId =;

    var newPost = new Post({ id: argId, likes: 2 }); (err) {
        if (err) {
            return response.json({ message: err });

        return response.json({ message: true });

module.exports = router;
If you have followed the posts so far you will see there is no database specific connection objects or init calls cluttering up the business logic. In addition Mongoose made saving objects extremely easy by having a save function on the object.

Next up...

Overall simply adding in Mongoose has cleaned up my code, next up is the configuration component to remove the hard coded port number and database connection information. All of the code thus far is committed on GitHub..
none on this post