Search code examples
node.jsmongodbexpressroutesget

how to use 2 parameter route get node.js


How to use 2 parameter in 1 route (get) this is my code

router.get('/', function (request, response) {
        Result.find(function(error, results){
        if (error) console.log(error)

        response.render('index', {results:results})
      })
    })

router.get('/', function (request, response) {
        Result.count({stuff:"book"}, function(error, count){
        if(error) console.log(error)

        response.render('index', {count})
      })
    })

I have tried to combine to be like this but i got an error

router.get('/', function (request, response, next) {
        Result.find(function(error, results){
        if (error) console.log(error)

        response.render('index', {results:results})
      }),
        Result.count( {stuff:"book"}, function(error, count){
        if(error) console.log(error)

        response.render('index', {count})
      })
    })

#note : if I use one of them is running perfectly (nothing error), but I need 2 parameter..


Solution

  • To send both pieces of data to your template, you will have to collect both pieces of data in one route handler and then call res.render() once with both pieces of data.

    You only get to send one response for an incoming request so if you want to render the template with multiple pieces of data, then you collect all that data and call res.render() once, passing it all the data it needs and your template should be configured to expect all the data to be passed to it at once:

    // use database callbacks and nest the two calls
    router.get('/', function(request, response, next) {
        Result.find(function(error, results) {
            if (error) {
                console.log(error)
                response.sendStatus(500);
                return;
            }
            Result.count({ stuff: "book" }, function(error, count) {
                if (error) {
                    console.log(error)
                    response.sendStatus(500);
                    return;
                }
                response.render('index', { count, results });
            });
        });
    });
    

    Or, using the promise interface on your database (which I presume it has):

    // using Promises and Promise.all() to run both queries in parallel
    router.get('/', function(request, response, next) {
        Promise.all([Result.find(), Result.count({ stuff: "book" })]).then(([results, count]) => {
            response.render('index', { count, results });
        }).catch(err => {
            console.log(error);
            response.sendStatus(500);
        });
    });