首页 > 解决方案 > 如何在 MongoDB 中以对象格式保存或获取数据

问题描述

当我执行获取用户模型的获取请求时,我正在获取对象数组。

[ { followers: [],
 followings: [],
 posts: [],
 _id: 5bb04fccnkj8a813e6,
 firebase_id: 'cBeDoamGaiH3',
 name: 'Sujoy Saha',

 __v: 0 } ]

但我希望它采用以下格式。即。嵌套对象格式。

{ followers: [],
followings: [],
posts: [],
_id: 5bb04fccnkj8a813e6,
firebase_id: 'cBeDoamGaiH3',
name: 'Sujoy Saha',

__v: 0 }

这是我的用户架构

const userSchema = new mongoose.Schema({
firebase_id:{
    type: String,
    required:true
},
name:{
    type: String,
    required: true
},

followers:[
    {
        type: String 
    }
],
followings:[
    {
        type: String
    }
]
});

我必须为此做出什么改变?

标签: node.jsmongodb

解决方案


方案本身很好。您正在使用的获取请求可能find会返回数组中的多个文档。这就是为什么你会看到一个数组包裹着你的对象。尝试使用findByIdorfindOne获取单个文档,它将作为object而不是返回array


推荐阅读