Reputation: 111
I'm stuck in using req.params.id to execute a query with Mongoose. I use Angular but the problem don't come from here.
I just put the code that concern my server and my route files
routes.js
var Product = require('./models/product'); // My Mongoose model
var express = require('express');
var router = express.Router(); // Do I really need that ?
// function to retrieve ALL employees (working)
function getEmployees(res){
Employee.find(function(err, employees) {
if (err)
return res.send(err)
res.json(employees);
});
};
// function to retrieve ONE employee (not working)
function getEmployeeByID(req,res){
var query = Employee.where({ _id: req.params.id });
query.findOne(function (err, employee) {
if (err)
return res.send(err)
res.json(employee);
});
};
module.exports = function(app) {
// !!!!!!!!!!! PROBLEM IS HERE !!!!!!!!!!!!!!!
app.get('/employees/:employee_id', function(req, res) {
getEmployeeByID(res);
});
// ALL IS WORKING HERE
app.get('/employees', function(req, res) {
getEmployees(res);
});
app.post('/employees', function(req, res) {
Employee.create({
firstname : req.body.firstname,
lastname : req.body.lastname,
age : req.body.age,
dept : req.body.dept,
done : false
}, function(err) {
if (err)
res.send(err);
getEmployees(res);
});
});
app.delete('/employees/:employee_id', function(req, res) {
Employee.remove({
_id : req.params.employee_id
}, function(err) {
if (err)
res.send(err);
getEmployees(res);
});
});
app.use('/', router);
module.exports = router;
}; // end module.exports
Then I have my server file
// modules =================================================
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var db = require('./config/db');
mongoose.connect(db.url);
var port = process.env.PORT || 8080; // set our port
var router = express.Router();
// application -------------------------------------------------------------
router.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // pass our application into our routes
app.listen(port);
module.exports = app;
The problem is that when I land on the employees page, I have an error :
GET http://localhost:8080/employees/undefined 500 (Internal Server Error)
It's normal since I've not clicked yet an employee so no ID.
BUT, still, even with a click on one employee, it's ID is not retrieved. I mean, the URL is changed with /employees/employee_id but it won't find the ID in the function getEmployeeByID. In Terminal all the console.log give UNDEFINED even after clicking on ONE employee.
I tried many examples and rode the Docs on Express 4 but can't find what's wrong.
Thanks you if you can help.
Upvotes: 2
Views: 10325
Reputation:
I solved this problem.
userController.js
exports.getUser = (req, res) => {
const _id = req.params.id
UserModel.findById(_id).then((user) => {
if (!user) {
return res.status(404).send()
}
res.send(user)
}).catch((error) => {
res.status(500).send(error)
})
}
router.js
router.get('/users/:id', userController.getUser)
Upvotes: 1
Reputation: 191
You have an error in the way you call the getEmployeeByID
function.
The function signature expects req
then res
, but you are sending only res
to it, which will be wrongly treated as req
inside the function.
Also, you should refer to the param with the name you gave it, meaning req.params.employee_id
.
Now you should actually use the router
instead of app
which is the more classic way of doing it in Express4.
function getEmployeeByID(req, res){
var query = Employee.where({ _id: req.params.employee_id }); // <-- Use the correct param name
query.findOne(function (err, employee) {
if (err)
return res.send(err)
res.json(employee);
});
};
module.exports = function(app) {
// User router instead of app
router.get('/employees/:employee_id', function(req, res) {
getEmployeeByID(req, res); // <-- sending both req and res to the function
});
I've never used moongoose (am a mongodb native driver user) so can't comment on that part of the code.
Upvotes: 2