Can you dig it?

Modeling Mongo Documents With Mongoose

Aug 29th, 2012

Without a doubt, one of the quickest ways to build an application that leverages MongoDB is with Node. It’s as if the two platforms were made for each other; the sheer number of Node libraries available for dealing with Mongo is testimony to a vibrant, innovative community. Indeed, one of my favorite Mongo focused libraries these days is Mongoose.

Briefly, Mongoose is an object modeling framework that makes it incredibly easy to model collections and ultimately work with intuitive objects that support a rich feature set. Like most things in Node, it couldn’t be any easier to get set up. Essentially, to use Mongoose, you’ll need to define Schema objects – these are your documents – either top level or even embedded.

For example, I’ve defined a words collection that contains documents (representing…words) that each contain an embedded collection of definition documents. A sample document looks like this:

Word Document

123456789101112

{_id:"4fd7c7ac8b5b27f21b000001",spelling:"drivel",synonyms:["garbage","dribble","drool"],definitions:[{part_of_speech:"noun",definition:"saliva flowing from the mouth, or mucus from the nose; slaver."},{part_of_speech:"noun",definition:"childish, silly, or meaningless talk or thinking; nonsense; twaddle."}]}

From an document modeling standpoint, I’d like to work with a Word object that contains a list of Definition objects and a number of related attributes (i.e. synonyms, parts of speech, etc). To model this relationship with Mongoose, I’ll need to define two Schema types and I’ll start with the simplest: