Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

query in express mongoose

//controllers/tourController.js
const Tour = require('./../models/tourModel');
exports.getAllTours = async (req, res) => {
  try {
    const queryObj = { ...req.query };
    const excludeFields = ['page', 'sort', 'limit', 'fields'];
    excludeFields.forEach((el) => delete queryObj[el]);

    //build a query
    const query = Tour.find(queryObj);
    //execute query
    const tours = await query;

    res.status(200).json({
      status: 'sucess',
      results: tours.length,
      data: {
        tours,
      },
    });
  } catch (error) {
    res.status(404).json({
      status: 'fail',
      message: error,
    });
  }
};
 
PREVIOUS NEXT
Tagged: #query #express #mongoose
ADD COMMENT
Topic
Name
1+6 =