filter a query string with comparison operator

Solutions on MaxInterview for filter a query string with comparison operator by the best coders in the world

showing results for - "filter a query string with comparison operator"
Cassie
09 Jul 2020
1//if need to find ratings greater then 3
2//The query string may be:
3//127.0.0.1:8000/api/v1/posts?ratings[gt]=3
4//if we check the req.query
5//{ ratings: { gt: '3' } }
6
7
8exports.getPosts = async (req, res) => {
9try {
10    const queryObj = { ...req.query };
11    let queryStr = JSON.stringify(queryObj)
12    queryStr = queryStr.replace(/\b(gt|gte|lt|lte|eq|ne)\b/g, match => `$${match}`);
13    // queryStr  : {"ratings":{"$gt":"3"}}
14    const posts = await Post.find(JSON.parse(queryStr));
15    res.json({
16        status: 'success',
17        data: {
18            posts
19        }
20    })
21} catch (err) {
22    res.status(401).json({
23        status: 'error',
24        message: 'Error in post finding',
25        error: err
26    })
27}}
28