Suppose I have 3 MongDB entries in a movie database:
"books": [
{
"_id": "xxxxxx",
"title": "Fast Five",
"rating": 6
},
{
"_id": "yyyyyy",
"title": "Kill Bill",
"rating": 8
},
{
"_id": "zzzzzzzz",
"title": "Jumanji",
"rating": 5
}
]
I use GraphQL to retrieve the id of multiple movies if their title and rating match the criteria:
query{
getMovies(itemFilterInput: {titles:["Fast Five", "Jumanji"], rating:6}){
_id
title
}
}
This should return Fast Five. I want this to translate into a mongoDB query like this:
{$and: [{rating:6}, {$or: [{title:"Fast Five", title:"Jumanji"}]}]}
In the backend, I use NodeJS and Mongoose to handle this query and I use something like this:
getMovies: async args => {
try{
let d = args.itemFilterInput;
let filters = new Array();
const keys = Object.keys(d);
keys.forEach((key) => {
// The titles case
if(d[key] instanceof Array){
var sObj = {};
var sObjArray = [];
d[key].map(prop => {
sObj[key] = prop;
sObjArray.push(sObj);
});
filters.push({$or: sObjArray});
}else{
// The rating case
var obj = {};
obj[key] = d[key];
filters.push(obj);
}
});
const items = await Item.find({$and: filters});
return items.map(item => {
return item;
});
} catch (err) {
throw err;
}
}
Unfortunately, this approach does not work. What is the correct way to nest $or parameters in $and params?
Answer:
First of all, it is better to use the $in operator instead of a $and/$or combination.
And to solve the error: use quotes everywhere to declare the query.