简体   繁体   中英

Parse string to object to query from mongo db

I am trying to use a query parameter with mongo db, i sent the string as

"{"location.city":"Florida"},{"category":"sports"}"

i need to pass this as a condition, so i am trying to remove the "" with the following code.

let filter = JSON.parse(myString);

but it throws an error Unexpected token , in JSON at position 27'

Expected format:

{"location.city":"Florida"},{"category":"sports"}

For mongodb query parameters you need to use JSON object and what you have is string, which represent comma-delimited list of objects. If you've got this string from somewhere you would need to parse it and convert it to the object(s). For example you would separate this string by "," (comma), go through each element of the array of strings and convert them to the JSON object with JSON.parse . If this is string you have created on your own as the query for mongodb request, you did it wrong. As I said you have comma-delimited list, but you should have object or if you need, array of objects inside the query object. Something like ...

{"location.city":"Florida","category":"sports"}
// or
{"myData": [{"location.city":"Florida"},{"category":"sports"}]}

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