javascript - 带通配符的 Mongoose 查询 Where 子句

标签 javascript node.js mongoose

我有一个如下的 Mongoose 查询

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

  });

它返回所有使用 Windows 操作系统的计算机 记录。

现在我想用一个变量 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将两种查询类型合二为一,但我预计这会对性能产生影响。

关于javascript - 带通配符的 Mongoose 查询 Where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962063/

相关文章:

node.js - Npm 在单独的目录中安装 DevDependencies

javascript - 如何在 Node.js 中使用我的 PHP 正则表达式?

node.js - Usergrid node.js usergrid.init() 错误

javascript - 创建 MEAN API 路由错误

javascript - 对象数组在 .push() 之后不显示内容

javascript - 如何在 JavaScript 中动态设置对象的属性

javascript - jQuery 滑动/淡入淡出功能

node.js - 蒙戈 : add fields with count of how many times another field appears

javascript - 调用工厂定义的方法返回未定义的值/ promise

javascript - 当一页上有多个表时,Jquery Mobile Column Toggle 附加按钮