Reputation: 8297
I am new to RESTful APIs and I've successfully implemented the GET and DELETE methods for my API (GET localhost:4000/api, DELETE localhost:4000/api on Postman works fine).
What I want to implement now is to specify the order in which to sort each specific field where 1 is ascending and -1 is descending. For example,
If I do localhost:4000/api/users?sort = { fieldName : 1 }
This will return a list of users sorted by 'fieldName'.
I tried to do
router.get('/', function(req, res) {
var sort = req.query.sort;
user
.find({})
.sort({"name": sort})
.exec(function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK',
data: users
});
}
});
});
But since the "name" part is hard-coded, it only works for names. I want to let the user specify the field name and sort the list based on it.
What do I have to add?
EDIT: This is how my data looks like
{
"message": "OK",
"data": [
{
"_id": "59faba588f3f6211ac7db43c",
"name": "Kim2",
"email": "[email protected]",
"__v": 0,
"dateCreated": "2017-11-02T06:25:28.225Z",
"pendingTasks": []
},
{
"_id": "59facf56e8c5663343d4b644",
"name": "Minnie Payne",
"email": "[email protected]",
"__v": 0,
"dateCreated": "2017-11-02T07:55:02.552Z",
"pendingTasks": []
},
{
"_id": "59fb699c3c00c60990fa6edb",
"name": "jerry watson",
"email": "[email protected]",
"__v": 0,
"dateCreated": "2017-11-02T18:53:16.637Z",
"pendingTasks": []
}, ...
EDIT2
user
.find({})
.sort('name')
.exec(function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK sorted',
data: users
});
}
});
Upvotes: 0
Views: 740
Reputation: 2220
What you want to do is to name an object property by a string. To do it you can do something like:
var string = 'name'
var obj = {}
obj[string] = 'val'
console.log(obj) // {name: 'val'}
So, in your example:
router.get('/', function(req, res) {
var sort = req.query.sort;
var name = req.query.name;
var obj = {}
obj[name] = sort
user
.find({})
.sort(obj)
.exec(function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK',
data: users
});
}
});
});
EDIT: solution with localhost:4000/api/users?sort={fieldName: 1}
router.get('/', function(req, res) {
let obj = JSON.parse(req.query.sort)
user
.find({})
.sort(obj)
.exec(function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK',
data: users
});
}
});
});
Upvotes: 1