MongoDb Node.js查询嵌套对象无法正常工作?

时间:2017-09-20 16:34:38

标签: javascript node.js mongodb

我需要使用mongodb的node.js驱动程序查询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()方法不接受对象文字。我无法找到它完全接受的文件。

1 个答案:

答案 0 :(得分:0)

您的_id属性需要位于查询对象中,而不是分开。

以下是如何操作:

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

collections.find(query);
相关问题