1

Is there a (proper) way to use the $oroperator in a URL query string to realize a client customizable query which does not only consist of and combined fields against my node.js powered RESTful API?

Let's say I have objects like

[{
  A: 1,
  B: 2,
  C: 42
}, {
  A: 3,
  B: 1,
  C: 42
}]

How do I query the MongoDB using mongoose to get both of them if searched in multiple fields? Something like $and: [{C:42}, $or: [{A:1}, {B:1}]] as URL parameters?

I tried GET /api/orders?$or=[{A:1},{B:1}]], but that results in a query like orders.find({ '$or': '[{A:1},{B:1}]]' }}), where the array is a string. The MongoDB driver then complains about $or needs an array.

All libraries like mongo-querystring have some complex operators for $gtand so on, but not for a simple OR of parameters. What am I missing here?

My goal is to build a convience search field, where the user can enter a simple string which then in turn is searched in multiple fields, returning all documents where at least one field (or a substring of that field) matches. So the frontend should decide in which fields and how the server should search, leading to a dynamic set of AND/OR combined field/value pairs.

Thanks in advance,

Ly

1 Answer 1

2

One option is to use the qs library which is a querystring parser with nested object support.

const qs = require('qs');

const query = {$or:[{A:1},{B:1}]};

let stringQuery = qs.stringify(query);

console.log(stringQuery); // => %24or%5B0%5D%5BA%5D=1&%24or%5B1%5D%5BB%5D=1
console.log(qs.parse(stringQuery)); // => { '$or': [ { A: '1' }, { B: '1' } ] }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply, that is one decent way to do it. I ended doing the parsing myself, but that's basically the solution.
Thanks. As a side note, the unencoded query string looks like this: $or[0][A]=1&$or[1][B]=1
@Seeven You said the "unencoded query string looks like this: $or[0][A]=1&$or[1][B]=1" how do you make it match the example above parse result?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.