Reputation: 2683
I have a simple comments app which enables the user to enter a comment into the system via a form and these are then logged onto a list on the bottom of the page.
I wanted to modify it so that a user could click a comments title once it is created and it would load up the associated content that goes with that comment.
I have modified my route in the app.js to lookup the :id
:
And have also modified my main Show.js route to use the id
as an argument in a findOne
command to locate the comment.
I have also put in a console.log()
command to log out the req.params.id
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);
router.get('/', function(req, res) {
Comment.findOne({ id: req.params.id }, function(err, comment){
console.log(req.params.id)
});
});
module.exports = router;
However, all I am getting back is an undefined
message in my terminal.
If I place the console.log()
directly in my app.js, I get the id logged as intended.
app.use('/:id', function(req,res) {
console.log(req.params.id)
});
Am I missing something in my route that is stopping my from getting the id parameter?
Upvotes: 1
Views: 3861
Reputation: 11
You need to pass {mergeParams: true} when calling your router in the router page
var router = express.router({mergeParams: true})
this will pass the parent parameters to the child.
Upvotes: 1
Reputation: 4238
You need to specify the :id
in your get route, like this:
// GET /1 -> print 1
router.get('/:id', function(req, res) {
console.log(req.params.id);
});
// GET /foo/1/bar/2 -> print 1, print 2
router.get('/foo/:id1/bar/:id2', function(req, res) {
console.log(req.params.id1);
console.log(req.params.id2);
});
Upvotes: 2