Sorry for the poorly formulated question..
Here is the code:
module.exports.getUserByQuery = function (params, callback) {
if (params.nationality.length !== 0 && params.languages.length !== 0) {
User.find(
{
age: {
$gt: params.minAge,
$lt: params.maxAge,
},
nationality: { $in: paramas.nationality},
languages: { $in: params.languages },
},
callback
);
} else if (params.nationality.length === 0 && params.languages.length === 0) {
User.find(
{
age: {
$gt: params.minAge,
$lt: params.maxAge,
},
},
callback
);
} else if (params.nationality.length !== 0 && params.languages.length === 0) {
User.find(
{
age: {
$gt: params.minAge,
$lt: params.maxAge,
},
nationality: { $in: params.nationality },
},
callback
);
} else if (params.nationality.length === 0 && params.languages.length !== 0) {
User.find(
{
age: {
$gt: params.minAge,
$lt: params.maxAge,
},
languages: { $in: params.languages },
},
callback
);
}
};
Params.nationality and language can be an empty string array if the website user didn't choose a value in the search engine.
Is there a value I could set them to that would make the filter act as if it didn't exist?
I'm basically looking for a way to get rid of the ifs.
CodePudding user response:
I don't think you can completely eliminate the conditions, but you can structure your code to be better manageable like this (for example):
let params = { minAge: 10, maxAge: 12, nationality: [ ], languages: [ ] }
const filterBuilder = function(params) {
const f1 = {
age: {
$gt: params.minAge,
$lt: params.maxAge
}
}
const f2 = { nationality: { $in: params.nationality } }
const f3 = { languages: { $in: params.languages } }
if (params.languages.length !== 0 && params.nationality.length !== 0) {
Object.assign(f1, f2, f3);
} else if (params.languages.length !== 0) {
Object.assign(f1, f3);
} else if (params.nationality.length !== 0) {
Object.assign(f1, f2);
}
return f1;
}
User.find(filterBuilder(params), callback);