Mongoose Where Where wildcard query

I have a mongoose request as shown below

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

  });

      

It returns all computer

records from the Windows

OS.

Now I want to use a variable osType

to replace the parameter with a equals

more flexible one.

Can I substitute a wildcard *

in a variable osType

? I tested it and it doesn't work.

var osType = '*';

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

  });

      

Or what are the alternatives for this?

Please do not delete the sentence where

as I want it to be used for osType=windows, linux ...

etc.

+3


source to share


1 answer


I think you will 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 do this:

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

      

Alternatively you can use Query#regex

to dump both types of queries into one, but I expect this to have a performance impact.

+3


source







All Articles