Mongoose find( )

mtee

Margaret W.N

Posted on July 20, 2020

Mongoose find( )

Find is an inbuilt mongoose method chained to the model and used to filter and find particular data. Find ( ) can take three parameters

  • A query filter/ condition
student.find({ firstName: jane });
//Returns all the data with the firstName as Jane
Enter fullscreen mode Exit fullscreen mode

NB: We need not to worry about type conversion to objectIds, Mongoose handles that for us.

  • Query projections. Defines the data to be excluded or included in the search results.
student.find({ firstName: jane }, `firstName major`);
//Returns the specified fields - firstName and major
Enter fullscreen mode Exit fullscreen mode
  • General query options such limit ( ), skip( ), sort( ) e.t.c
student.find({ firstName: jane }, `firstName major`, { Limit: 10 });
//Limits the search to  the first 10 results
student.find({ firstName: jane }, `firstName major`, { skip: 2 });
//Skips the first 2 results.
Enter fullscreen mode Exit fullscreen mode

Callback function. After data is retrieved you'll want to pass the results to callback function

student.find({ firstName: jane }, `firstName major`, { Limit: 10 }, (err, students) => {});
//Callback arrow function
Enter fullscreen mode Exit fullscreen mode

FindById ( )

Gets a single Item by Id

student.findById(req.params.bookId, (err, student) => {});
//Retrieves a single item.
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
mtee
Margaret W.N

Posted on July 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Password authentication
100daysofcode Password authentication

August 11, 2020

HTTP Post Verb
100daysofcode HTTP Post Verb

July 21, 2020

Mongoose find( )
100daysofcode Mongoose find( )

July 20, 2020

Working With MongoDB
100daysofcode Working With MongoDB

July 19, 2020