带有通配符的Mongoose查询Where子句



我有一个猫鼬查询,如下

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

它使用Windows操作系统返回所有computer记录。

现在,我想使用变量osType来替换equals参数,使其更加灵活。

我可以为osType变量提供通配符*吗?我测试了它,但它不起作用。

var osType = '*';
Computer
    .find()
    .where('OS').equals(osType)
    .exec(function(err, items) {
  });

或者实现这一目标的替代方案是什么?

请不要删除where子句,因为我希望它用于osType=windows, linux ...等…

我认为您将不得不在这两个语句之间切换:

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

和:

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

你可以重写你的代码来适应它:

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

或者,您可以使用Query#regex将两种查询类型合并为一种,但我预计这会对性能产生影响。

最新更新