Answers for "filter a query string with comparison operator"

0

filter a query string with comparison operator

//if need to find ratings greater then 3
//The query string may be:
//127.0.0.1:8000/api/v1/posts?ratings[gt]=3
//if we check the req.query
//{ ratings: { gt: '3' } }


exports.getPosts = async (req, res) => {
try {
    const queryObj = { ...req.query };
    let queryStr = JSON.stringify(queryObj)
    queryStr = queryStr.replace(/\b(gt|gte|lt|lte|eq|ne)\b/g, match => `$${match}`);
    // queryStr  : {"ratings":{"$gt":"3"}}
    const posts = await Post.find(JSON.parse(queryStr));
    res.json({
        status: 'success',
        data: {
            posts
        }
    })
} catch (err) {
    res.status(401).json({
        status: 'error',
        message: 'Error in post finding',
        error: err
    })
}}
Posted by: Guest on June-23-2021

Code answers related to "filter a query string with comparison operator"

Code answers related to "Javascript"

Browse Popular Code Answers by Language