peter vries
peter vries

Reputation: 173

MongoDB check if value exists within array

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!

Upvotes: 0

Views: 4935

Answers (2)

Tomov Nenad
Tomov Nenad

Reputation: 164

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"] }

Upvotes: 0

Alex Blex
Alex Blex

Reputation: 37048

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

Upvotes: 1

Related Questions