freeCodeCamp/guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-.../index.md

2.0 KiB

title
Chain Search Query Helpers to Narrow Search Results

Chain Search Query Helpers to Narrow Search Results

  1. To create but not execut a find query
Model.find( {name: 'Leah'} )

      

  1. To store the find query into a variable for later use:
var findQuery = YourModel.find( {name: 'Leah'} )

      

  1. To sort an array:
yourArray.sort( {age: 1} )  // Here: 1 for ascending	order and -1 for descending order.

      

  1. To limit an array's size:
yourArray.limit(5)  // return array which has 5 items in it.

      

  1. To hide certain property from the result:
yourArray.select( {name: 0, age: 1} ) // Here: 0 means false and thus hide name property; 1 means true so age property will show.

      

  1. To exec this query, you can either:
      1) Callback:
YourQuery.exec(function(err, docs) {
    //do something here
})

      Or 2) Promise

YourQuery.exec.then(function(err, docs) {
    //do something here
})
  1. Chain it all together:
Person.find({age: 55}).sort({name: -1}).limit(5).select( {favoriteFoods: 0} ).exec(function(error, people) {
  //do something here
})


This is a stub. Help our community expand it.

This quick style guide will help ensure your pull request gets accepted.