richie
richie

Reputation: 197

passing multiple collections to the same express route

app.get('/dbpage', function(req, res){            
        Chapters.find({}, function(err, allChapters){
        if(err){
            console.log(err);
        }else{
            res.render('dbpage', {chapters: allChapters});
        }
    });
});

The code above is a small portion of my project, and it's working fine. Chapters is the collection's name which is part of my books database. But I have another collection (from the same database) that I'm trying to pass through the same route /dbpage. How would add this other collection to the code above? So I can access the information stored in this other collection in the /dbpage route.

I've seen some other answers that are more or less suited for what I'm trying to do, but they all seen overkill for such a simple thing. Any suggestions? Thanks!!

Upvotes: 0

Views: 523

Answers (1)

dvsoukup
dvsoukup

Reputation: 1596

You can't invoke the same route name. If you use duplicate route definitions, the one "listed first" will take precedence. The only time the same route definition is allowed is if you utilize a different HTTP verb... such as POST, PUT, PATCH, etc.

Thus, if you truly want to use the same route, you need to pass query params and then push conditional logic in the route, such as:

app.get('/dbpage', function(req, res){
        let {someQueryParam} = req.query;
        if(someQueryParam === 'someSpecialValue'){
          //... do something different...     
        } else {       
          Chapters.find({}, function(err, allChapters){
          if(err){
              console.log(err);
          }else{
              res.render('dbpage', {chapters: allChapters});
          }
        }
    });
});

And, you'd invoke it with some endpoint such as:

yourDomain.com:3000/dbPage?someQueryParam="someSpecialValue"

Honestly though I'd advise against introducing conditional logic when at all possible. If possible, just set up another endpoint.

Upvotes: 1

Related Questions