loading...

Mongoose find( )

mtee profile image Margaret W.N ・1 min read

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

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
  • 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.

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

FindById ( )

Gets a single Item by Id

student.findById(req.params.bookId, (err, student) => {});
//Retrieves a single item.

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide