繁体   English   中英

.find()使用动态属性名称的嵌套对象

[英].find() nested object using dynamic property names

我需要使用Node.js驱动程序在MongoDb中找到嵌套对象。

属性名称为dynamic时,我无法访问嵌套属性。 这是我的代码:

//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)

这是数据库结构的示例:

{
   "_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
      }
   }
}

编辑:我的问题不是标记为重复的重复。 MongoDb find()参数不是对象文字。 这就是我的问题的全部重点,像对象文字一样使用它不起作用。

最后我自己找到了解决方案。 密钥必须是字符串,因此您需要执行以下操作:

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

collection.find(query)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM