I am new to RESTful APIs and I've successfully implemented the GET and DELETE command for my API (GET localhost:4000/api, DELETE localhost:4000/api on Postman works fine).
Code for my get looks like:
router.get('/', function(req, res) {
user.find({}, function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK',
data: users
});
}
});
});
Now I want to implement using parameters. For example, I want to implement something like sorting where
http://localhost/4000/api/users?sort={"name": 1} (1- ascending; -1 - descending)
would mean sorting the name in ascending order.
What I am not sure how to do is:
How do I make the ?sort thing work?
How do I select which field to sort?
Please help!
You can only pass order(asc, desc), if you want to sort by name you can do like that http://localhost/4000/api/users?order=-1 or http://localhost/4000/api/users?&order=1
then in your controller
router.get('/', function(req, res) {
let order = req.query.order;
user
.find({})
.sort({"name": order})
.exec(function(err, users) {
if(err){
res.status(404).send({
message: err,
data: []
});
} else {
res.status(200).send({
message: 'OK',
data: users
});
}
});
});
These works if you use mongoose.js for mongodb
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加