Home REST API - Node, Express, MySQL - How can I filter a JSON (from DB) return by passing a limited number of objects via URL
Reply: 3

REST API - Node, Express, MySQL - How can I filter a JSON (from DB) return by passing a limited number of objects via URL

Silvio Custodio
1#
Silvio Custodio Published in 2018-01-12 14:10:48Z

I'm building a REST API, using Node, Express, MySQL.

When requesting a list of Node from the http://localhost:3000/Node endpoint, I would like to limit these to only 25 initial records. This could be accomplished with a request like GET http://localhost:3000/Node?maxRecords=25.

My routes\Nodes file is:

var express = require('express');
var router = express.Router();
var Node=require('../models/Node');

router.get('/:id?',function(req,res,next){

    if(req.params.id){
        Node.getNodeById(req.params.id,function(err,rows){

            if(err)
            {
                res.json(err);
            }
            else{
                res.json(rows);
            }
        });
    }

    else{
        Node.getAllNodes(function(err,rows){

            if(err)
            {
                res.json(err);
            }
            else
            {
                res.json(rows);
            }
        });
    }
});
module.exports=router;

And in my models\Node.js (that is passing queries to db) is:

var db=require('../dbconnection');

var Node={

    getAllNodes:function(callback){

        return db.query("Select * from node_link",callback);

    },
    getNodeById:function(id,callback){

        return db.query("select * from node_link where id=?",[id],callback);
    }

}
module.exports=Node;
Abhyudit Jain
2#
Abhyudit Jain Reply to 2018-01-12 14:13:25Z

You can use LIMIT in the query.

http://www.mysqltutorial.org/mysql-limit.aspx

Grigory Babajanyan
3#
Grigory Babajanyan Reply to 2018-01-12 14:55:32Z

In your models/Node.js:

getAllNodes: function(maxRecords, callback) {

  return db.query("Select * from node_link LIMIT ?", [maxRecords], callback);

}
Arthur Guiot
4#
Arthur Guiot Reply to 2018-01-12 14:55:23Z

The LIMIT attribute in your query will help, it will limit the number of rows outputted.
So, with this in mind, your query should look like:

SELECT * FROM node_link LIMIT 10

If you want more rows, just increase the 10 by whatever you want 😊.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.410213 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO