最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose Query Where Clause with Wildcard - Stack Overflow

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论