【发布时间】:2018-04-15 16:11:24
【问题描述】:
我是 RESTful API 的新手,我已经成功地为我的 API 实现了 GET 和 DELETE 方法(POST 上的 GET localhost:4000/api,DELETE localhost:4000/api 工作正常)。
我现在要实现的是指定每个特定字段的排序顺序,其中 1 为升序,-1 为降序。例如,
如果我做 localhost:4000/api/users?sort = { fieldName : 1 }
这将返回按“fieldName”排序的用户列表。
我试过了
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
});
}
});
});
但由于“名称”部分是硬编码的,它只适用于名称。我想让用户指定字段名称并根据它对列表进行排序。
我要补充什么?
编辑:这就是我的数据的样子
{
"message": "OK",
"data": [
{
"_id": "59faba588f3f6211ac7db43c",
"name": "Kim2",
"email": "kk2@gmail.com",
"__v": 0,
"dateCreated": "2017-11-02T06:25:28.225Z",
"pendingTasks": []
},
{
"_id": "59facf56e8c5663343d4b644",
"name": "Minnie Payne",
"email": "minnie@gmail.com",
"__v": 0,
"dateCreated": "2017-11-02T07:55:02.552Z",
"pendingTasks": []
},
{
"_id": "59fb699c3c00c60990fa6edb",
"name": "jerry watson",
"email": "jerry@wgmail.com",
"__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
});
}
});
【问题讨论】:
-
req.query项目都是“字符串”。如果您希望 JSON 中的对象作为参数值,请使用JSON.parse。即.sort({ name: JSON.parse(req.query.sort) })其中req.query.sort是“字符串”'{ "fieldName": 1 }'。注意 JSON 需要引用的“键”。 -
抱歉,您能否在答案中详细说明您的解决方案?我想我明白了,但我真的不明白如何在代码中执行此操作。