How to do it...

  1. Create a new file named chaining-queries.js
  1. Include the Mongoose NPM module. Then, create a new connection:
      const mongoose = require('mongoose') 
      const { connection, Schema } = mongoose 
      mongoose.connect( 
          'mongodb://localhost:27017/test' 
      ).catch(console.error) 
  1. Define a schema:
      const UserSchema = new Schema({ 
          firstName: String, 
          lastName: String, 
          age: Number, 
      }) 
  1. Compile the schema into a model:
      const User = mongoose.model('User', UserSchema) 
  1. Once connected to the database, add a new document to the collection of users. Then, using chaining syntax, query for the recently created user. Additionally, use the select method to restrict which fields are retrieved from the document:
      connection.once('connected', async () => { 
          try { 
              const user = await new User({ 
                  firstName: 'John', 
                  lastName: 'Snow', 
                  age: 30, 
              }).save() 
              const findUser = await User.findOne() 
                  .where('firstName').equals('John') 
                  .where('age').lte(30) 
                  .select('lastName age') 
              console.log(JSON.stringify(findUser, null, 4)) 
              await user.remove() 
          } catch (error) { 
              console.dir(error.message, { colors: true }) 
          } finally { 
              await connection.close() 
          } 
      }) 
  1. Save the file
  2. Open a Terminal and run:
    node chaining-queries.js
  
..................Content has been hidden....................

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