skip to Main Content

i have a payload

{
    "category": "Mobile",
    "price": {
        "from": "10",
        "to": "50"
    },
    "location": [
        "Jakrta",
        "Bandung",
        "Surabaya"
    ],
    "rating": [
        "1",
        "2",
        "3"
    ]
}

i want to find all object which have rating 1 or 2 or 3 and also have any location
Basically i am creating a filter for an ecommerce store i which we will get multiple location and multiple ratings as well so we will return only those object which have matched property. i am attaching a screenshot of UI for better understanding.
i want to run this filter with multiple location and multiple checked checkbox

2

Answers


  1. If you want to filter your objects, you should use filter() from your array :

    const arr = [{
        "category": "Mobile1",
        "price": {
            "from": "10",
            "to": "50"
        },
        "location": [
            "Jakrta",
            "Bandung",
            "Surabaya"
        ],
        "rating": [
            "1",
            "2",
            "3"
        ]
    },
                {
        "category": "Mobile2",
        "price": {
            "from": "10",
            "to": "50"
        },
        "location": [
            "Jakrta",
            "Bandung",
            "Surabaya"
        ],
        "rating": [
            "2",
            "3"
        ]
    }];
    
    const result = arr.filter(el => el.rating.includes("1") || el.rating.includes("2") || el.rating.includes("3"));
    
    console.log(result);
    Login or Signup to reply.
  2. You can do create a filter dynamically:

    const { category, price, location, rating } = req.body;
    
    const filter = {};
    
    if (category) filter.category = category;
    if (price) filter.price = { $gte: parseInt(price.from, 10), $lte: parseInt(price.to, 10) };
    if (location?.length) filter.location = { $in: location };
    if (rating?.length) filter.rating = { $in: rating };
    
    const data = await Collection.find(filter);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search