ak85
ak85

Reputation: 4264

Conditional query in Mongoose with integers in query

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 partialy 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(version);
}

Another issue with the above snippet is if I am looking for a string eg title and title starts with a number eg 7up, then this returns no results either.

var title= req.query.title;
var query = Model.find();
if (version) {
    query = query.where('title').equals(title);
}

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?

Below is a snippet of my data model, once I can get this working I intend to add more items that are either numbers or strings

    var ModelSchema = new Schema({
        version: {
            type: Number,
            trim: true
        },
        color: {
            type: String,
            trim: true
        },
        title: {
            type: String,
            trim: true
        },    
    });

    mongoose.model('Model', ModelSchema);

Upvotes: 0

Views: 671

Answers (1)

Brian Shamblen
Brian Shamblen

Reputation: 4703

If I follow your code it looks like you're trying to use a regular expression to search integers in your query, which doesn't make sense to me. You have conditions[key] = new RegExp('^' + parseInt(req.query[key]) + '$', 'i'); but you should be able to simply have conditions[key] = parseInt(req.query[key]);

Glad that worked. Thanks!

Upvotes: 1

Related Questions