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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With