【问题标题】:Retrieve all the keys of an object inside a mongoose document在 mongoose 文档中检索对象的所有键
【发布时间】:2021-01-02 12:26:23
【问题描述】:

我有一组文档。我正在使用猫鼬和快递。 每个文档都使用此架构构建:

const userSchema = new Schema({
    firstName: { type: String },
    lastName: { type: String },
    email: { type: String },
    books: { type: Object },
});
const User = mongoose.model('User', userSchema);

导出默认用户; 对于对象“books”中的每个文档,我可以有不同的“key:value”对。

例如, 第一份文件:

{
    "firstName": "Lucy",
    "lastName": "Red",
    "email": "lucy.red@mail.com",
    "books": {
        "Harry Potter" : "horrible",
        "Hunger Games" : "beautiful"
     }
}

第二份文件:

{
    "firstName": "Tom",
    "lastName": "Brown",
    "email": "tom.brown@mail.com",
    "books": {
        "The Great Gatsby" : "beautiful",
        "Frankenstein" : "horrible"
     }
}

我想做的是查询 db 集合,并在一个数组中获取可以在每个“books”对象中找到的所有可能的键。

对于这个例子,我想检索:

["Harry Potter" , "Hunger Games", "The Great Gatsby", "Frankenstein"];

是否存在这样做的方法?非常感谢。

【问题讨论】:

  • 作为一个建议,如果你将 books 对象放入一个带有子文档的数组中,例如 ``` { title: "Harry Potter", rating: "horrible" } ``` 它将使您的查询更简单

标签: javascript mongodb express mongoose mongodb-query


【解决方案1】:

试试下面的方法:

db.collection.aggregate([
    {
        
         $project: {
            books: { $objectToArray: "$books" }
         }
      
    },
    {
        $unwind: "$books"
    },
    {
        $group: {
            _id: null,
            books: { $push: "$books.k"  }
        }
    }
])

结果如下:

{
    "_id" : null,
    "books" : [
        "Harry Potter",
        "Hunger Games",
        "The Great Gatsby",
        "Frankenstein"
    ]
}

【讨论】:

  • 这可能是解决方案,但如果我有重复的键,此解决方案会将它们推入数组中。我怎么能避免这种情况?我想让我的数组没有重复的键。
  • 好的,我已经通过 "res.json([...new Set(booksCollection[0].books)]);" 解决了这个问题在我的 api 里面
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 2016-09-09
  • 2019-02-07
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多