Mongoose查询带通配符的子句

时间:2015-06-21 06:55:57

标签: javascript node.js mongoose

我有一个猫鼬查询,如下所示

1*50 + 3*5 + 2*1 = 67

它返回Computer .find() .where('OS').equals('Windows') .exec(function(err, items) { }); 操作系统的所有computer条记录。

现在我想使用变量 Windows来替换osType参数,以便更灵活。

我可以为equals变量提供通配符*吗?我测试过它并没有用。

osType

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

请不要删除var osType = '*'; Computer .find() .where('OS').equals(osType) .exec(function(err, items) { }); 条款,因为我希望它用于where等...

1 个答案:

答案 0 :(得分:3)

我认为你将不得不在这两个陈述之间切换:

// 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将两种查询类型合并为一种,但我希望这会对性能产生影响。