Reputation: 43
Is there a (proper) way to use the $or
operator 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 $gt
and 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
Upvotes: 1
Views: 2665
Reputation: 2079
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' } ] }
Upvotes: 2