2

I need to find nested objects in MongoDb using the Node.js Driver.

I'm having trouble accessing nested properties when the property name is dynamic. Here's my code:

//This gives expected results but "name1" isn't dynamic
collection.find({ 'followers.name1': { $exists: false } })

//Here's what I tried that does not give expected results
const username = "name1"
let query = { followers: {} }
query.followers[username] = { $exists: false } 

collection.find(query)

Here's an example of the database structure:

{
   "_id":"xxxxxxxxxxx",
   "dateAdded":"2017-09-20T08:36:40.325Z",
   "followers":{
      "name1":{
         "followedOn":"2017-09-20T08:36:40.325Z",
         "unfollowedOn":null
      },
      "name2":{
         "followedOn":"2017-09-20T08:36:40.325Z",
         "unfollowedOn":null
      }
   }
}

Edit: my question is not a duplicate of the one marked as a duplicate. MongoDb find() argument is not an object literal. That's the whole point of my question, using like it like an object literal doesn't work.

cooldude101
  • 1,215
  • 2
  • 14
  • 29
  • can i have a sample db which shows how data is stored – Vignesh Sep 20 '17 at 09:55
  • according to your question `followers` is static and `name1` is dynamic correct me if i am wrong – Vignesh Sep 20 '17 at 10:13
  • @Vignesh correct – cooldude101 Sep 20 '17 at 10:21
  • `{ foo: bar }` *is* an object literal in JavaScript. It doesn't matter what you do with the object later, the answer will still be the same. So yes, your question is indeed a duplicate. – Ilmari Karonen Sep 20 '17 at 20:46
  • @IlmariKaronen It's not the same, you can't do query.followers[username], you need to do query['followers.'+username] . It's a duplicate of other questions relating to mongodb nodejs querying, but not a duplicate of the question marked as duplicate at the time. – cooldude101 Sep 21 '17 at 07:22

1 Answers1

1

I found the solution myself in the end. The key needs to be a string so you need to do:

const username = 'name1'
let query = {}
query['followers.'+username] = { $exists: false } 

collection.find(query)
cooldude101
  • 1,215
  • 2
  • 14
  • 29