Modeling Mongo documents with Mongoose

1 2 Page 2
Page 2 of 2
findOne in action
<span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<code class='javascript'><span class='line'><span class="nx">it</span> <span class="s1">'findOne should return one'</span><span class="p">,</span> <span class="p">(</span><span class="nx">done</span><span class="p">)</span> <span class="o">-></span>
</span><span class='line'>  <span class="nx">models</span><span class="p">.</span><span class="nx">Word</span><span class="p">.</span><span class="nx">findOne</span> <span class="nx">spelling</span><span class="o">:</span><span class="s1">'nefarious'</span><span class="p">,</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nb">document</span><span class="p">)</span> <span class="o">-></span>
</span><span class='line'>    <span class="nb">document</span><span class="p">.</span><span class="nx">spelling</span><span class="p">.</span><span class="nx">should</span><span class="p">.</span><span class="nx">eql</span> <span class="s1">'nefarious'</span>
</span><span class='line'>    <span class="nb">document</span><span class="p">.</span><span class="nx">definitions</span><span class="p">.</span><span class="nx">length</span><span class="p">.</span><span class="nx">should</span><span class="p">.</span><span class="nx">eql</span> <span class="mi">1</span>
</span><span class='line'>    <span class="nb">document</span><span class="p">.</span><span class="nx">synonyms</span><span class="p">.</span><span class="nx">length</span><span class="p">.</span><span class="nx">should</span><span class="p">.</span><span class="nx">eql</span> <span class="mi">2</span>
</span><span class='line'>    <span class="nb">document</span><span class="p">.</span><span class="nx">definitions</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="s1">'part_of_speech'</span><span class="p">].</span><span class="nx">should</span><span class="p">.</span><span class="nx">eql</span> <span class="s1">'adjective'</span>
</span><span class='line'>    <span class="nx">done</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span>
</span></code>

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!

This story, "Modeling Mongo documents with Mongoose" was originally published by JavaWorld.

Related:

Copyright © 2012 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2