1

I try to filter my outcome from MongoDB. I'm using an Express. Here are my console.logs:

  1. req.query.filters from URL: http://localhost:3000/test?filters=%7Bpersonalbest%3A%7B%27%24gt%27%3A%27170%27%7D%2Cname%3A%7B%27%24gt%27%3A%27M%27%7D%7D
  2. an object made by me to test if that works with my database and it does
  1. {personalbest:{'$gt':'170'},name:{'$gt':'M'}}
  2. { personalbest: { '$gt': '170' }, name: { '$gt': 'M' } }

Code:

var filters = req.query.filters
db.collection('skijumper').find(filters).toArray()

And of course I get this error:

MongoError: query selector must be an object

What is the best way to convert this req.query to an object ? Thanks

  • Anything in `req.params` or `req.query` is simply a "string". There is in fact `bodyParser` middleware for making `req.body` content into an actual object. You probably should be sending the object in `body` instead. But essentially `JSON.parse` the "string" into an "object". Which means you likely need to "quote" in urlencoding as well. So it seems a lot easier to send in the request body instead. – Neil Lunn Aug 01 '17 at 10:26
  • Thank you, I appreciate your help! – Michał Bednarz Aug 01 '17 at 10:42

1 Answers1

2

Frontend:

var filters = {personalbest:{'$gt':'170'},name:{'$gt':'M'}};
var url = "http://localhost:3000/test?filters=" + encodeURIComponent(JSON.stringify(filters));

Backend:

var filters = JSON.parse(req.query.filters);
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82