Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Query Where Clause with Wildcard

I have a mongoose query as the below

Computer
    .find()
    .where('OS').equals('Windows')
    .exec(function(err, items) {

  });

It returns all computer records with Windows OS.

Now I want to use a variable osType to replace the equals parameter to be more flexible.

Can I supply a wildcard * to the osType variable? I tested it and it is not working.

var osType = '*';

Computer
    .find()
    .where('OS').equals(osType)
    .exec(function(err, items) {

  });

Or what are the alternatives to achieve this?

Please do not delete the where clause as I want it to be used for osType=windows, linux ... etc...

like image 986
Xianlin Avatar asked Sep 27 '22 13:09

Xianlin


1 Answers

I think you're going to have to switch between these two statements:

// If you have a specific value you want to find:
Computer.find().where('OS').equals(osType).exec(...)

And:

// All documents that have a `OS` property:
Computer.find().where('OS').exists().exec(...)

You can rewrite your code to accommodate for that:

var query = Computer.find().where('OS');
if (osType === '*') {
  query = query.exists();
} else {
  query = query.equals(osType);
}
query.exec(...);

Alternatively, you could use Query#regex to fold both query types into one, but I expect this will have a performance impact.

like image 83
robertklep Avatar answered Sep 30 '22 05:09

robertklep