I am working through a MEAN stack tutorial. It contains the following code as a route in index.js
. The name of my Mongo collection is brandcollection
.
/* GET Brand Complaints page. */
router.get('/brands', function(req, res) {
var db = req.db;
var collection = db.get('brandcollection');
collection.find({},{},function(e,docs){
res.render('brands', {
"brands" : docs
});
});
});
I would like to modify this code but I don't fully understand how the .find
method is being invoked. Specifically, I have the following questions:
What objects are being passed to function(e, docs)
as its arguments?
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 .find
operation is collection.find({},{}).someCursorLimit()
. I have not seen a reference to a third parameter in the .find
operation, so why is one allowed here?
If function(e, docs)
is not a MongoDB operation, is it part of the Monk API?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With