Node.js + MongoDB = Mongoose

Mongoose is a ORM like library that helps a lot when you want to access your collections defined on MongoDB from Node.js. You can use it without schemas but by defining ORM objects the code becomes much easier to read.

After you install Mongoose by npm install mongoose you can do the following to start playing with:

var mongoose = require('mongoose').Mongoose;
var db = mongoose.connect('mongodb://localhost/goaljuice');


To define a model:

mongoose.model('User', {
  collection: 'user',
  properties: [
    'created',
    'username',
    'password',
    'email'
  ],
  indexes: [
    'created',
    [{username: 1},{unique: true}],
    [{email: 1},{unique: true}]
  ],
  static: {},
  methods: {},
  setters: {},
  getters: {}
  }
);

To create the model on MongoDB and have a ORM “class”:

var User = db.model('User');

Now, you have a user collection under goaljuice database. After that you can create new User instances and do CRUD operations:

var user = new User();
user.created = new Date();
user.username = "TEST";
user.password = "PASS";
user.email = "someemail";
user.save();

One thing you may notice is that you can have a Date object as one of the fields. In addition to that, you can do comparison queries on Date objects. However, I don’t know (yet) if it’s better to have an integer of seconds for a created field instead of a Date object. At the moment, I enjoy having a full Date object while coding.

One annoying problem I’ve encountered at the moment is that since I’ve a unique restriction on username and email MongoDB gives error in case of duplicates (so it protects itself very well) but Mongoose library ignores this error. In that respect, you have to do your own checks if a record already exists or not.

Another problem is that if you don’t define your unique indexes at the beginning Mongoose ORM does not alter the index later when you add the uniqueness restriction. In such cases you need to drop the collection on MongoDB or add the unique restriction yourself.

At the end, Mongoose looks like the library I will use for my project to connect MongoDB and Nodejs.

This entry was posted in nodejs, nosql, sips and tagged , . Bookmark the permalink.

2 Responses to Node.js + MongoDB = Mongoose

  1. ed says:

    Nice help, 1 year later and surprisely continues been used :D

  2. gf4g7456s46 says:

    Mongoose is too a project of a simple, functional, embeddable web server

    https://code.google.com/p/mongoose/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>