0

I'm using MongoDB inside a twig framework. I'm trying to determine if the user has access to a certain module.

(a part of) my DB entry looks like:

 _id: "579b50a4f5092761a20f4e71",
approvedModules: [
 "examplemodule",
 "examplemodule1",
 "examplemodule2",
 "examplemodule3"
],

My code looks like:

session.get('__AUTH_USER').find({ approvedModules : { '$in' : ["examplemodule"]}}, { '$exists' : true })

(the standard functions have to be in quotes).

I keeps returning false. I can only return the value if I use session.get('__AUTH_USER').approvedModules.0 I don't want to include the .0 because that might change.

What am I doing wrong?

Thanks in advance!

2
  • 1
    Have you tried $elemMatch - docs.mongodb.com/manual/reference/operator/query/elemMatch Commented Aug 29, 2016 at 13:00
  • Thanks for the reply! Yeah, but I get the same problem: session.get('__AUTH_USER').find({ approvedModules: { '$elemMatch' : { wildcard?!: "examplemodule"} } }, { '$exists' : true }) Commented Aug 29, 2016 at 13:05

2 Answers 2

1

What am I doing wrong?

Many things. The worst one is using queries to database inside a template, but it is another problem.

You misunderstood purpose of the $in operator, which is used to match a field in the database to any element of array in the query.

To match any element of array in the collection to a single value you can do simple $eq:

session.get('__AUTH_USER').find({ approvedModules : "examplemodule"})
Sign up to request clarification or add additional context in comments.

9 Comments

Did you try it without { '$exists' : true } ? It is another thing you are doing wrong.
yes, but why is that wrong? - to clarify, its inside an {%if %} statement
Because the second parameter of find is a projection which specifies which fields to output.
so what would be the right way to check if the user has 'examplemodule1' in the array 'approvedModules' ?
First of all, you don't need to search database, if you already know who user is. Fetch it, hydrate into an object, use normal PHP object in the template without hitting database. With your current approach you can do .find({_id: "579b50a4f5092761a20f4e71", approvedModules : "examplemodule1"}).count() == 1
|
0

When you are using $in operator, you need to have 2 input arguments, the first one is the value for which you are checking the array, and the second one should be the array itself. So, your bson element should look like this: isModuleInArray : { '$in' : ["examplemodule","$approvedModules"] }

Comments

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.