Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

node.js - How to pass to sort function req.query.sort?

I have a router that is supposed to retrieve sorted data, using node and mongoose

router.get('/api/users/',
async (req:Request, res:Response)=> {

const users = await User.find({}).sort();

res.send(users);

});


User.find({}).sort();

req.query.sort = ["name","DESC"] as a string not an array and not an object!

as I know sort expects to Json object but JSON.parse() not work. assume because the square brackets.

I wonder what is the right way to deal with it?

question from:https://stackoverflow.com/questions/66045630/how-to-pass-to-sort-function-req-query-sort

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use body-parser module so just try in index file

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

and in router file :

let item : string[]= JSON.parse(req.query.sort);
let object = {}
object[item[0]] = item[1];
const users = await User.find({}).sort(object)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...