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: [
  indexes: [
    [{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"; = "someemail";;

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 uniquerestriction 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.

Mongoose 로 blog 를 만들어 보겠어. ㅋㅋㅋ

hackya 는

Attorney, front-end developer, digital media artist, WordPress enthusiast, & a father of 4 wonderful children.

Tags: , ,



Leave a Reply

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