Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Query MongoDB - Node.js

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 :: AJAX in reload a div container 
Javascript :: trim function 
Javascript :: understanding currying 
Javascript :: classlist toggle 
Javascript :: javascript this inside arrow function 
Javascript :: lettre au hasard javascript 
Javascript :: basic area chart 
Javascript :: js object 
Javascript :: JavaScript is case-sensitive 
Javascript :: javascript null 
Javascript :: counting pairs in an array, resulting in a given sum 
Javascript :: what is javascript 
Javascript :: eventlistener javascript 
Javascript :: js timer 
Javascript :: scribbletune 
Javascript :: jquery function called onDeleteMovie. This function should be invoked upon clicking the Delete button of each one of the movie templates 
Javascript :: react native store sensitive data in redux 
Javascript :: move li to bottom of list jquery selected value 
Javascript :: frame-grab js 
Javascript :: elon musk 4k photo 
Javascript :: string .length js 
Javascript :: js camelcase 
Javascript :: return <Text using if condition react native 
Javascript :: express rate limit redis 
Javascript :: serverresponse 
Javascript :: generate tabuada java script 
Javascript :: how does a dictionary from c# translate into js 
Javascript :: paypal cordova can not open popup window - blocked 
Javascript :: selected css based on route react 
Javascript :: javascript middleware getter and setter 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =