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:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
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:
1 2 3 4 |
|
As you can see, a Definition
is simple – the part_of_speech
attribute is an enumerated String
that’s required; what’s more, the definition
attribute is also a required String
.
Next, I’ll define a Word
:
1 2 3 4 5 |
|
As you can see, a Word
instance embeds a collection of Definition
s. Here I’m also demonstrating the usage of lowercase
and the index unique
placed on the spelling
attribute.
To create a Word
instance and save the corresponding document couldn’t be easier. Mongo array’s leverage the push
command and Mongoose follows this pattern to the tee.
1 2 3 4 5 |
|
Finding a word is easy too:
1 2 3 4 5 6 7 |
|
In this case, the above code is a Mocha test case (which uses should for assertions) that demonstrates Mongoose’s findOne
.
You can find the code for these examples and more at my Github repo dubbed Exegesis and while you’re at it, check out the developerWorks videos I did for Node!