Reputation: 68
I need help how to sorting response data according to schema.
This is my schema
const RoleModel = new Schema({
name : {...
},
description:{...
},
permission:{...
}
},{timestamps: false})
and here my current response
{
"message": "Displaying data",
"data": [
{
"permission": {...
},
"_id": "615b378a3eca06e2194c2204",
"name": "SuperAdmin",
"__v": 0
},
{
"permission": {...
},
"_id": "615b396f3eca06e2194c220a",
"name": "Reporter",
"__v": 0
},
{
"permission": {...
},
"_id": "615b39dea1e3f384847014d1",
"name": "Finance",
"description": "nodescription",
"__v": 0
}
]
}
I want the response data sorted like this
"data" : [
{
"_id" :615b378a3eca06e2194c2204, // first key
"name": superadmin, // second key
"permission":{...}, // third key
"__v": 0 // last key
},
{
"_id" :615b378a3eca06e2194c2204, // first key
"name": superadmin, // second key
"permission":{...}, // third key
"__v": 0 // last key
}
...
]
Should I create a new variable with defined key object and assign each data to it or there is a right way to do it?
Thankyou
Upvotes: 0
Views: 224
Reputation: 162
You can use project
methodology in find()
in mongodb to display how you want to.
Below I have the code for you:
db.studentdatas.find({},{_id:1, name:1, permission: 1, __v:1}).sort({name:1})
1 in find() depicts you want that field to be seen/projected which is in {}.
You will not require sorting here. But if you want to sort data any field based on the data it has then you can use sort()
either 1 or -1.
And to display the data of response you can write in nodejs/expressjs:
res.send(response.data)
where your response.data
is what you mentioned in your question :
"data" : [
{
"_id" :615b378a3eca06e2194c2204, // first key
"name": superadmin, // second key
"permission":{...}, // third key
"__v": 0 // last key
},
{
"_id" :615b378a3eca06e2194c2204, // first key
"name": superadmin, // second key
"permission":{...}, // third key
"__v": 0 // last key
}
...
]
I hope this is what you wanted to ask.
Upvotes: 1