Using Mongoose query builders

Every Mongoose model has static helper methods to do several kinds of operations, such as retrieving a document. When a callback is passed to these helper methods, the operation is executed immediately:

      const user = await User.findOne({ 
          firstName: 'Jonh', 
          age: { $lte: 30 }, 
      }, (error, document) => { 
          if (error) return console.log(error) 
          console.log(document) 
      }) 

Otherwise, if there is no defined callback, a query builder interface is returned, which can be later executed:

      const user = User.findOne({ 
          firstName: 'Jonh', 
          age: { $lte: 30 }, 
      }) 
      user.exec((error, document) => { 
          if (error) return console.log(error) 
          console.log(document) 
      }) 

Queries also have a .then function which can be used as a Promise. When .then is called, it first executes the query internally with .exec which then returns a Promise. This allows us to use async/await as well. Inside a async function, for instance:

      try { 
          const user = await User.findOne({ 
              firstName: 'Jonh', 
              age: { $lte: 30 }, 
          }) 
          console.log(user) 
      } catch (error) { 
          console.log(error) 
      }  

There are two ways that we can make a query. One is by providing a JSON object that is used as a condition and the other way allows you to create a query using chaining syntax. The chaining syntax will feel more comfortable to developers who are more familiar with SQL databases. For example:

      try { 
          const user = await User.findOne() 
        .where('firstName', 'John') 
              .where('age').lte(30) 
          console.log(user) 
      }       catch (error) { 
          console.log(error) 
      }  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.51.241