Search code examples
node.jsmongodbmonk

Trouble using mongodb $ positional indicator in nodejs with monk.js


I am trying to perform a search on my database and return the roles a user has for an application and store that in their session.

The end state being in their session I now have user.applications =

[
    {
    "_id": "oehgf12083310f1h30f",
    "name": "Internal",
    "roles": {
                 "send": true,
                 "create_template": true,
                 "edit_template": true
             }
    }
]

The applications data structure:

[
    {
        "_id": "oehgf12083310f1h30f",
        "name": "Internal",
        "permissions": [
            {
                "username": "username2",
                "roles": {
                    "send": true,
                    "create_template": true,
                    "edit_template": true
                }
            },
            {
                "username": "username1",
                "roles": {
                    "send": true,
                    "create_template": true,
                    "edit_template": false
                }
            }
        ]
    }
]

Using the mongodb console

I can perform this search and returns exactly what I need to populate the user.applications object in their session:

db.applications.find({
  "permissions.username": "username2"
}, {
  "permissions.$": true,
  name: true
}).pretty()

This returns all applications that username2 has access to, while returning the level of permissions they have, and only them. So excludes username1 object

In nodejs using monk

find({
  "permissions.username": "username2" || req.query.username
}, {
  "permissions.$": true,
   name: true
}, function(err, docs) {});

Now this search returns the user objects for username2 AND username1, which is problematic as I then have to process that even further to extract the correct permissions.

Questions

I suspect monk does something to my search that leaves it unable to use the $ positional indicator, but if I am wrong, please let me know how I can use it to achieve what I am after.

Otherwise any other ideas/approaches I could that to achieve that end state would be greatly appreciated :)


Solution

  • Maybe this helps:

    find({permissions.username": "username2" || req.query.username }, { "permissions": { "$elemMatch": {"username": "username2"}}, name: true}, function(err, docs) {});