Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Error: Can't use $or with String

This is a very strange issue and I was not able to fix it. My piece of code with query is this one:

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);
            }
        });
    }
});

when i called this query i got response as

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

I ran above query in the MongoClient RoboMongo & it worked! Where is the problem in the query programmatically?

like image 338
Shaggie Avatar asked Aug 23 '17 14:08

Shaggie


2 Answers

I don't know why exactly it doesn't work (maybe looking at mongoose) but if someone wants to get this request working, here is a solution that works for me :

userTypeModel.find({
  name : {
    $in : [
      'ADMIN',
      'SUPERADMIN'
    ]
  },
  activeStatus : 1 }, function (err, userTypeRow) {...})
like image 83
Fabien Avatar answered Nov 07 '22 10:11

Fabien


StringSchema doesn't seem to support logical operators, except for $not. While debugging a similar error I backtraced it to the core of the problem. These are the only operators that the schema supports:

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

So yeah, this kind of problem can be solved via $in or $regex.

I guess its for excluding a scenario when user can combine mutually exclusive rules on one single field like

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

In most cases such nonsense should produce no results, but who knows what internal cloggege can this cause?

like image 20
Spown Avatar answered Nov 07 '22 12:11

Spown