DEV Community

Margaret W.N
Margaret W.N

Posted on

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

Oldest comments (0)