jdw jdw - 5 months ago 74
Node.js Question

Using the find method on a MongoDB collection with Monk

I am working through a MEAN stack tutorial. It contains the following code as a route in

. The name of my Mongo collection is

/* GET Brand Complaints page. */
router.get('/brands', function(req, res) {
var db = req.db;
var collection = db.get('brandcollection');
res.render('brands', {
"brands" : docs

I would like to modify this code but I don't fully understand how the
method is being invoked. Specifically, I have the following questions:

  1. What objects are being passed to
    function(e, docs)
    as its arguments?

  2. Is
    function(e, docs)
    part of the MongoDB syntax? I have looked at the docs on Mongo CRUD operations and couldn't find a reference to it. And it seems like the standard syntax for a Mongo
    operation is
    . I have not seen a reference to a third parameter in the
    operation, so why is one allowed here?

  3. If
    function(e, docs)
    is not a MongoDB operation, is it part of the Monk API?

  4. It is clear from the tutorial that this block of code returns all of the documents in the collection and places them in an object as an attribute called "brands." However, what role specifically does
    function(e, docs)
    play in that process?

Any clarification would be much appreciated!


The first parameter is the query.

The second parameter(which is optional) is the projection i.e if you want to restrict the contents of the matched documents

collection.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 },function(e,docs){})

would mean to get only the item and qty fields in the matched documents

The third parameter is the callback function which is called after the query is complete. function(e, docs) is the mongodb driver for node.js syntax. The 1st parameter e is the error. docs is the array of matched documents. If an error occurs it is given in e. If the query is successful the matched documents are given in the 2nd parameter docs(the name can be anything you want).

The cursor has various methods which can be used to manipulate the matched documents before mongoDB returns them. collection.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 }) is a cursor you can do various operations on it.

collection.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 }).skip(10).limit(5).toArray(function(e,docs){

meaning you will skip the first 10 matched documents and then return a maximum of 5 documents.

All this stuff is given in the docs. I think it's better to use mongoose instead of the native driver because of the features and the popularity.