0

I'm trying to query for a user which has an array within an array. I can get the mongo shell command working fine, although the node.js command won't work, just showing "found user" without a user object concatenated.

Shell (working):

  db.users.find(
    {
      "username":"gregpmillr", 
      "completed_modules": {
                            "$elemMatch": {
                                            "module": {
                                                      "$elemMatch": {
                                                                      "module_id":ObjectId("59a0d98e9df98d39e0760faf")
                                                                    }
                                                      }
                                          }
                            }
    }
  ).pretty()

Node.js (no returned user):

User.find(
  {
    "username":username, 
    "completed_modules": [{ 
                          "module": [{
                                      "module_id": module_id
                                    }]
                         }]
  }
)
.exec()
.then(user => {
  if (user) {
    console.log("found user: " + user);
  } else {
    console.log("no matched user");
  }
})

Where User is a model, username is logged in user, module_id is simply the _id for another collection.

Probably something small that I'm missing. I tried to follow Node.js driver docs as much as I could but couldn't really find the answer since I don't believe $elemMatch works with the driver.

Any ideas?

2
  • $elemMatch is part of the query DSL. If you are looking for it "in the driver" then it's not documented in the driver because it has nothing to do with it. The DSL is language independent and works everywhere. As noted in the linked answer, it's likely you really need "dot notation" as usage of $elemMatch is commonly misunderstood ( even though clearly documented as to the difference ) as being required for matching array elements, when it is actually not. Commented Sep 13, 2017 at 3:38
  • I don't agree that this is an exact duplicate, as I'm using an array and couldn't find out how to use dot notation. I just had to add mongoose.Types.ObjectId(module_id) instead of simply module_id. Commented Sep 15, 2017 at 1:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.