Debug School

rakesh kumar
rakesh kumar

Posted on

How to retrive data from collection using $lt and $gt command

Filter data using lt commands

Model (user.js):

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  city: String
});

module.exports = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

Controller (userController.js):

const User = require('../models/user');

const UserController = {
  getUsersByAgeRange: async (req, res) => {
    try {
      const minAge = 20;
      const maxAge = 30;

      const users = await User.find({ age: { $gt: minAge, $lt: maxAge } });

      res.render('users', { users });
    } catch (error) {
      console.log('Error:', error);
      res.status(500).send('An error occurred');
    }
  }
};

module.exports = UserController;
Enter fullscreen mode Exit fullscreen mode

Route (routes.js):

const express = require('express');
const router = express.Router();

const UserController = require('../controllers/userController');

router.get('/users', UserController.getUsersByAgeRange);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

View (users.ejs or users.hbs):

<h1>Users</h1>
<ul>
  <% users.forEach(user => { %>
    <li><%= user.name %> (Age: <%= user.age %>) - <%= user.city %></li>
  <% }); %>
</ul>
Enter fullscreen mode Exit fullscreen mode

In this example, the User model represents a user with name, age, and city fields.

The UserController contains a method named getUsersByAgeRange, which demonstrates the usage of the $gt and $lt operators. It retrieves users whose ages fall within the specified range. The method uses User.find({ age: { $gt: minAge, $lt: maxAge } }) to perform the query. The users with ages greater than minAge and less than maxAge will be selected.

The route file defines a route that handles the request for users. It maps the getUsersByAgeRange method in the controller to the corresponding route.

The view file displays the retrieved users' information in a list format using a loop (forEach in this case). The user's name, age, and city are rendered for each user.

This example showcases how the $lt and $gt operators can be utilized within the MVC framework in Node.js and MongoDB. The controller handles the logic, the model represents the data structure, the route maps the request to the appropriate controller method, and the view displays the information of the retrieved users.

Another Example

Model (product.js):

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: String,
  price: Number,
  quantity: Number
});

module.exports = mongoose.model('Product', productSchema);
Enter fullscreen mode Exit fullscreen mode

Controller (productController.js):

const Product = require('../models/product');

const ProductController = {
  getProductsByPriceRange: async (req, res) => {
    try {
      const minPrice = req.body.minPrice; // Minimum price obtained from req.body
      const maxPrice = req.body.maxPrice; // Maximum price obtained from req.body

      const filter = {
        price: { $gt: minPrice, $lt: maxPrice }
      };

      const products = await Product.find(filter);

      res.json(products);
    } catch (error) {
      console.log('Error:', error);
      res.status(500).send('An error occurred');
    }
  }
};

module.exports = ProductController;
Enter fullscreen mode Exit fullscreen mode

Route (routes.js):

const express = require('express');
const router = express.Router();

const ProductController = require('../controllers/productController');

router.get('/products', ProductController.getProductsByPriceRange);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

In this example, the Product model represents a product with name, price, and quantity fields.

The ProductController contains a method named getProductsByPriceRange, which takes the minimum price from req.body.minPrice and the maximum price from req.body.maxPrice. It constructs a filter object using the $gt (greater than) and $lt (less than) operators to match products within the specified price range. It then uses Product.find to retrieve products that fall within the given price range.

The route file defines a route that handles the GET request to retrieve products by price range. It maps the getProductsByPriceRange method in the controller to the corresponding route.

To use this functionality, you would need to make a GET request to the /products route, sending the minimum and maximum price in the request body. For example, using axios in a client-side JavaScript code:

axios.get('/products', {
  params: {
    minPrice: 10, // Minimum price
    maxPrice: 50 // Maximum price
  }
})
  .then(response => {
    const products = response.data;
    // Handle the retrieved products
  })
  .catch(error => {
    // Handle the error
  });
Enter fullscreen mode Exit fullscreen mode

This example demonstrates how you can use the query operators $lt and $gt with a dynamic query obtained from req.body in the context of the MVC pattern in Node.js and MongoDB. The controller handles the logic, the model represents the data structure, and the route maps the request to the appropriate controller method. In this

case, it retrieves products within a specified price range.

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Top comments (0)