I am looking at this question How to build a conditional query in Mongoose? And trying to build on it by handling integers in the query string.
I have the below code.
var conditions = {};
var patt = new RegExp('^[0-9]');
for (var key in req.query) {
if (req.query.hasOwnProperty(key)) {
if(patt.test(req.query[key])) {
conditions[key] = new RegExp('^' + parseInt(req.query[key]) + '$', 'i');
}
else {
conditions[key] = new RegExp('^' + req.query[key] + '$', 'i');
}
}
}
When I do &color=red this returns colors that equal red.
But when I do &version=2 etc I get nothing returned.
I have put a console log in my if statement to confirm that the patt regex is picking up the value starting with an int but this does seem to execute as I would expect (returning results where version = 2).
If I was to restructure my code as below, this does work. However this solution isn't really maintainable as I would need to add a condition for each potential param and need to go back and modify as more become available.
var version = parseInt(req.query.version);
var query = Model.find();
if (version) {
query = query.where('version').equals(gender);
}
Is there a solution I can use here that will allow me to use any param in the request and treat as an integer if it matches my patt regex?
Aucun commentaire:
Enregistrer un commentaire