Using find method in MongoDB collection with Monk

I am working on a MEAN tutorial. It contains the following code as a route in index.js . The name of my Mongolian 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 change this code, but I do not quite understand how the .find method is .find . In particular, I have the following questions:

  • What objects are passed to function(e, docs) as arguments?

  • Is function(e, docs) part of MongoDB syntax? I looked through the documents on Mongo CRUD operations and could not find a link to it. And it seems that the standard syntax for the Mongo .find operation is collection.find({},{}).someCursorLimit() . I did not see a link to the third parameter in the .find operation, so why is it allowed here?

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

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

Any clarifications would be greatly appreciated!

+6
source share
1 answer

The first parameter is the query.

The second parameter (which is optional) is the ie projection if you want to limit the content of the matched documents

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

would mean getting only the item and qty fields in consistent documents

The third parameter is a callback function that is called after the request completes. function(e, docs) is the mongodb driver for node.js. syntax The first parameter e is an error. docs is an array of consistent documents. If an error occurs, it is specified in e . If the request is successful, the consistent documents are given in the second parameter docs (the name can be whatever you want).

cursor has various methods that can be used to manage consistent documents before mongoDB returns them. collection.find ({qty: {$ gt: 25}}, {item: 1, qty: 1}) is a cursor on which you can perform various operations.

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

means that you skip the first 10 agreed documents and then return a maximum of 5 documents.

All these materials are given in the documents . I think it’s better to use mongoose instead of the native driver because of the features and popularity.

+12
source

Source: https://habr.com/ru/post/973289/


All Articles