简体   繁体   中英

Express + MongoDB - req.query to object

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM