3

I'm using mongodb and I've built to make the following query.

1 AccessToken.where('resource_owner_id').equals(event.resource_owner_id)
2           .where('revoked_at').equals(undefined)
3           .or([ { scopes: /resources/i }, { scopes: new RegExp(event.resource,'i') } ])
4           .or([ { device_ids: [] }, { device_ids: event.body.id } ])

For this example I'm using Mongoose and coffescript.

Unluckily it doesn't work as I want, mainly for the or statement. What I want is the two or on row 3 and 4 being independent.

This means that the field scopes (row 3) must contain the string resources or the string stored in event.resource, meanwhile the field device_ids must be empty or contain the id event.body.id.

From the tests I've prepared I can see that the or command put all together. This means that when just one of the four or conditions is satisfied I get the document.

- { scopes: /resources/i }
- { scopes: new RegExp(event.resource,'i') }
- { device_ids: [] }
- { device_ids: event.body.id }

What I'm not able to reach is to split them in two groups so that both the conditions related to the field scopes and the conditions related to the field device_ids can be satisfied.

Hope the problem is well described. Thanks.

1 Answer 1

8

Don't use $where unless you absolutely have to as performance is terrible. Use a combination of the $or and $size operators instead:

UPDATE There's no Mongoose and method so you have to use the $and operator directly.

AccessToken.find({
    resource_owner_id: event.resource_owner_id,
    revoked_at: undefined,
    $and: [
        { $or: [{ scopes: /resources/i }, { scopes: new RegExp(event.resource,'i') }] },
        { $or: [{ device_ids: { $size: 0 } }, { device_ids: event.body.id }] }
    ]
}, callback);
Sign up to request clarification or add additional context in comments.

3 Comments

This is similar to the solution I was coming out with. I updated the question as it was a bit more complex. The problem is that I would love to group the or in a way that one condition for scopes and one condition for device_ids should be satisfied.
@AndreaReginato To keep the two $or operations separate you have to put them in an $and operator. See updated answer.
Thanks a lot. I'll follow your detailed advices and let you know how things ended up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.