简体   繁体   English

将字符串解析为对象以从Mongo DB查询

[英]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 我正在尝试使用mongo db的查询参数,我将字符串发送为

"{"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' 但它在JSON的位置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. 对于mongodb查询参数,您需要使用JSON对象,而您拥有的是字符串,它表示以逗号分隔的对象列表。 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 . 例如,您可以使用“,”(逗号)分隔此字符串,遍历字符串数组的每个元素,然后使用JSON.parse将它们转换为JSON对象。 If this is string you have created on your own as the query for mongodb request, you did it wrong. 如果这是您自己创建的用于查询mongodb请求的字符串,那么您做错了。 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"}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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