Mongoose错误:无法使用$或使用String

时间:2017-08-23 14:18:46

标签: node.js mongodb mongoose

这是一个非常奇怪的问题,我无法修复它。我的查询代码是这一个:

userTypeModel.find({$or: [{name: 'ADMIN'}, {name: 'SUPERADMIN'}], activeStatus: 1}, function (err, userTypeRow) {

    if (err) {
        flowController.emit('ERROR', {message: "Unable to Get details! Try again " + err, status: 'error', statusCode: '500'});
    } else if (userTypeRow.length == 0) {
        flowController.emit('ERROR', {message: "No user-types available in the system yet!", status: 'error', statusCode: '404'});
    } else {
        var adminId = null;
        var superAdminId = null;

        async.eachSeries(userTypeRow, function (element, callback) {

            if (element.name == 'ADMIN') {

                adminId = String(element._id);
            }

            if (element.name == 'SUPERADMIN') {

                superAdminId = String(element._id);
            }

            callback();
        }, function (err) {

            if (err) {
                flowController.emit('ERROR', err);
            } else {
                flowController.emit('1', adminId, superAdminId);
            }
        });
    }
});

当我调用此查询时,我得到了响应

{
"message": "ERROR WHILE GETTING USERS Error: Can't use $or with String.",
"status": "error",
"statusCode": "500"
}

我在MongoClient RoboMongo&有效! 查询中的问题在哪里以编程方式?

3 个答案:

答案 0 :(得分:3)

我不知道为什么它无法正常工作(可能正在查看mongoose)但是如果有人想让这个请求有效,这里有一个适合我的解决方案:

userTypeModel.find({
  name : {
    $in : [
      'ADMIN',
      'SUPERADMIN'
    ]
  },
  activeStatus : 1 }, function (err, userTypeRow) {...})

答案 1 :(得分:0)

StringSchema似乎不支持logical operators,但$ not除外。在调试simmillar错误时,我将其回溯到问题的核心。这些是架构支持的唯一运算符:

$all
$eq
$exists
$gt
$gte
$in
$lt
$lte
$ne
$nin
$not
$options
$regex
$type

所以是的,这种问题可以通过$ in或$ regex来解决。

我想它可以排除用户可以在一个单独的字段上组合互斥规则的场景,例如

somefield: {$and: [
  {$or: [{$lt: 1}, {$gt: 1}]},
  {$and: [{$lt: 1}, {$gt: 1}]}
]  }

在大多数情况下,这样的无聊应该不会产生任何结果,但谁知道这会导致什么内部堵塞呢?

答案 2 :(得分:0)

此处记录了对此的答案:https://docs.mongodb.com/manual/reference/operator/query/or/#mongodb-query-op.-or

$or 与 $in

$or 与对同一字段的值进行相等性检查的“表达式”一起使用时,请使用 $in 运算符而不是 $or 运算符。

例如,要选择库存集合中数量字段值等于 20 或 50 的所有文档,请使用 $in 运算符:

db.inventory.find ( { quantity: { $in: [20, 50] } } )