Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

E.g query mongodb - node

const Books = require("Books.js")
async getBooks(req, res, next) {
    let query;

    // Copy req.query
    let reqQuery = { ...req.query };

    // Fields to exclude
    const removeFields = ["select", "sort"];

    // Loop over removeFields and delete them from reqQuery
    removeFields.forEach(param => delete reqQuery[param]);

    // Create query string
    let queryStr = JSON.stringify(reqQuery);

    // Create operators ($gt, $gte, etc)
    queryStr = queryStr.replace(
      /(gt|gte|lt|lte|in)/g,
      match => `$${match}`
    );

    // Find resource
    query = Books.findQuery(JSON.parse(queryStr));

    // Select Fields
    if (req.query.select) {
      const fields = req.query.select.split(",").join(" ");
      query = query.select(fields);
    }

    // Sort
    if (req.query.sort) {
      const sortBy = req.query.sort.split(",").join(" ");
      query = query.sort(sortBy);
    } else {
      query = query.sort("-createdAt");
    }

  
    // Pagination
    const page = parseInt(req.query.page, 10) || 1;
    const limit = parseInt(req.query.limit, 10) || 10;
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const total = await Books.countDocuments();
    query = query.skip(startIndex).limit(limit);
  
    // Executing query
    let books = await query;
  
  	
    // Pagination result
    const pagination = {};

    if (endIndex < total) {
      pagination.next = {
        page: page + 1,
        limit,
      };
    }

    if (startIndex > 0) {
      pagination.prev = {
        page: page - 1,
        limit,
      };
    }

    res.status(200).json({
      success: true,
      count: books.length,
      pagination,
      data: books,
    });
  
  
  }
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to sort an array 
Javascript :: js append html in div after 
Javascript :: namespace javascript 
Javascript :: build angular project 
Javascript :: template engine javascript 
Javascript :: random string javascript 
Javascript :: ex:javascript 
Javascript :: difference between =, == and === in javascript 
Javascript :: JavaScript finally() method 
Javascript :: Requiring express 
Javascript :: js classlist multiple classes 
Javascript :: es6 import 
Javascript :: angular mat side nav 
Javascript :: timer js 
Javascript :: reactjs change favicon 
Javascript :: javascript factorial stack 
Javascript :: mapview hooks glitch 
Javascript :: javascript change get parameter without reload 
Javascript :: mongoose fails to connect to server when database is specified 
Javascript :: load data table app script 
Javascript :: sort datatable c# 
Javascript :: scriptmanager call javascript function 
Javascript :: javascript select element have long word 
Javascript :: convert to jsx 
Javascript :: styleurls component angular node_modules 
Javascript :: scrollable div and unscrollable middle component 
Javascript :: no styles are appearing in angular calendar 
Javascript :: conflict paypal api javascript with user agent Mozilla/5.0 Google 
Javascript :: auto increment string in javascript 
Javascript :: bassed on text length find offset width in javascript 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =