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?

Greg Miller
  • 1,064
  • 13
  • 22
  • [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/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"](https://docs.mongodb.com/manual/core/document/#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. – Neil Lunn Sep 13 '17 at 03: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. – Greg Miller Sep 15 '17 at 01:13

0 Answers0