Sujoy
Sujoy

Reputation: 97

how to save or get data in object format in MongoDB

When i am doing a get request to get the user model, I am getting array of object.

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

 __v: 0 } ]

But i want it in the below format.ie. in nested object format.

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

__v: 0 }

this is my user schema

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

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

What change do i have to made for this?

Upvotes: 0

Views: 91

Answers (1)

Ron537
Ron537

Reputation: 990

The scheme itself is fine. The get request that you are using is probably find which returns multiple documents in an array. That's why you see an array wrapping your object. Try using findById or findOne to get a single document and it will be returned as an object instead of array

Upvotes: 2

Related Questions