我有一个如下的 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/