Javascript MongoDb Node.js查询嵌套对象不工作?

Javascript MongoDb Node.js查询嵌套对象不工作?,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我需要使用node.js驱动程序为mongodb查询2个动态属性 以下是数据结构: { "_id":"123456", "dateAdded":"2017-09-20T08:36:40.325Z", "followers":{ "name1":{ "followedOn":"2017-09-20T08:36:40.325Z", "unfollowedOn":null }, "name2":{

我需要使用node.js驱动程序为mongodb查询2个动态属性

以下是数据结构:

{
   "_id":"123456",
   "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
      }
   }
}
这是我的密码:

//Working but not dynamic
collections.find({ '_id': '123456', 'followers.name1': { $exists: false } })

//My failed attempt at making it dynamic
const id = "123456"
const username = "name1"

let query = {}
query['followers.'+username] = { $exists: true } 

collections.find( { "_id": id, query }

请注意,这不是“如何在对象文本中生成动态键”的重复。node.js mongodb驱动程序的.find()方法不接受对象文本。我找不到它确切接受什么的文档。

您的
\u id
属性需要位于查询对象中,而不是单独的

以下是如何做到这一点:

let query = { _id: id };
query['followers.'+username] = { $exists: true } 

collections.find(query);

您的
\u id
属性需要位于查询对象中,而不是单独的

以下是如何做到这一点:

let query = { _id: id };
query['followers.'+username] = { $exists: true } 

collections.find(query);