'Should we build Mongoose queries on the frontend or backend?

We can build complex queries with Mongoose with options like $lte, $gt, $ne and so on... but I'm wondering where/how we should build those queries?

If I have a form on my frontend that allows to input a range of dates I could send a request body that looks like this:

{
  date: {
    $gt: "01/01/2021",
    $lte: "31/01/2021"
  }
}

But is this good practice? If not, in what format should I send this and how can I transform it to a Mongoose query?



Solution 1:[1]

assuming you're sending that in the request body, then this isn't how you're supposed to do it, this can expose a security flaw in that your attackers can write queries themselves and retrieve confidential information seeing that your backend will run ANY query this can potentially be used to expose sensitive information.

Database is something the backend is supposed to handle, not the frontend, don't make the frontend write the queries. Instead just send dat a like this:

{
  "startDate": "1/1/1",
  "endDate": "2/2/2" 
}

Then on your backend you can get the values from the request body and do it yourself

{
  date: {
    $gt: startDate,
    $lte: endDate
  }
}

Solution 2:[2]

I have thought about this one as well. We currently have a few routes in our API that accept a custom query in the req.body like your example, however they are only "find" routes and they are protected by our authentication middleware. This made it easy to lookup documents by various properties in the front end VS building a route for each parameter.

Not sure if this is best practice but if we don't have faith in our authentication system then people can read all our data anyway, so I'm not sure how allowing them to send a custom query could make things worse?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 destroyer22719
Solution 2 Edward Hunt