Node.js Wiki
Advertisement

Mongoose is an ORM for Mongo, written in node.js. This is the new home of "Mongoose: the Missing Manual" formerly hosted on wonderlandlabs.com.

What it gives you[]

Mongoose in many ways "completes" Mongo in ways that most SQL people demand - that is:

  • It creates nested, typed schemas
    • Schema field specs can be as loose or specific as you like.
    • They can include type requirements (String, Number, Date... YourCustomType)
    • They can insist a record has a field value (Required)
    • They can be restricted to a set of values (a.k.a. Enum)
    • They can be set to a single or array of another Schema allowing arbitrarily nested documents.
  • It gives you transactional integrity
    • If the "non dirty" values for a record have changed since you retrieve a record, mongoose assumes that there is a transactional violation and rejects your changes when you save.
  • It employs the ActiveRecord pattern
  • It gives you Joins, foreign keys, and effortless map/reduce.
    • Well, not really. Sorry. But nobody else does either so there you go.
  • It gives you through and complete documentation.
    • Well -- the SCHEMA documentation is complete. But apparently there is nothing else important you will ever do with Mongo other than create schemas so that's pretty much all you get. For more detail read on...

What it demands of you[]

Well, before the existence of this article, a bit of psychic "spider sense" because the manual just stops when the author got bored with it.

In addition, every collection under Mongoose's control MUST have a FIXED, FINITE set of fields. For people coming from SQL this seems eminently sensible. Mongo people might not be so generous. I only drive this point home because Mongo people are likely to add fields willy mildly by simply setting a field value spontaneously and saving the ActiveRecord, then wonder where their data went.

If a field is not in your Schema - IT WILL NOT BE SAVED. Mongoose unlike Mongo does NOT accept any field you add passively - it actively looks like the fields defend in your Schema and saves THOSE and ONLY THOSE fields.

This edict is only nested one level deep. you can define a field with no restrictions and put ANYTHING you like in it as in:

var schema_def = {
  name: String,
  misc: {}
}

While the "name" field will take only a single string, you can put any (nested) piece of data you like into misc.

It also makes the assumption that when you shove data in Mongo you couldn't care less about the returned _id, because that precious bit of information evaporates into limbo without a bit of HACKING of the model library.

With that being said...[]

Here is a more thorough prod into the full cycle use of Mongoose.

Advertisement