javascript - Mongoose Query Where Clause with Wildcard - Stack Overflow

I have a mongoose query as the belowComputer.find().where('OS').equals('Windows').e

I have a mongoose query as the below

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

  });

It returns all puter 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 have a mongoose query as the below

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

  });

It returns all puter 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...

Share asked Jun 21, 2015 at 6:55 XianlinXianlin 1,1895 gold badges21 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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 acmodate 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744809145a4594960.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信