Evaldas Raisutis
Evaldas Raisutis

Reputation: 1638

How to I transform this sql into mongoose?

SELECT *
FROM user
WHERE (
      id_1 = '$entity_id' OR 
      id_2 = '$entity_id' OR  
      id_3 = '$entity_id' OR 
      id_4 = '$entity_id'
      ) AND 
      token = '$token'

I have model called "User". I need to check if user owns provided token and if at least one of the id_* matches $entity_id.

I've tried this, but didn't work:

mongoose.model('User').find(
        { 'local.token': req.query.token },
        {$or: [
            { "local._dormitory": req.params.id },
            { "local._building": req.params.id },
            { "local._hall": req.params.id },
            { "local._room": req.params.id }
        ]}, {}, function(err, doc){
        if(err) {
            console.log(err);
            return false;
        }
        if(doc != null) {
            console.log("Scope access exists");
            console.log(doc);
            return true;
            // res.json(200, { message: doc, Response: "true" });
        } else {
            console.log("Scope access doesn't exist");
            return false;
            // res.json(401, { message: "Auth failed" });
        }
    });

Upvotes: 0

Views: 61

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You need to put both parts of the query into the same query object:

mongoose.model('User').find(
    { 'local.token': req.query.token,
      $or: [
        { "local._dormitory": req.params.id },
        { "local._building": req.params.id },
        { "local._hall": req.params.id },
        { "local._room": req.params.id }
    ]}, {}, function(err, doc){
    ...

Upvotes: 1

Related Questions