Reputation: 83
I used the following code to delete an entry in mongodb
router.delete('/:id', function(req, res) {
Student.findByIdAndRemove(req.params.id, function(err, student) {
if(err) {
console.log(err);
return res.redirect('/students/' + req.params.id);
}
console.log('Deleted student.');
console.log(student);
res.redirect('/students');
});
});
The delete goes through, as I no longer see it in the database; however, if I visit the old page /students/:id it goes through instead of redirecting back and I receive an error because I'm attempting to use methods on null object.
router.get('/:id', function(req, res) {
Student.findById(req.params.id, function(err, foundStudent) {
if(err) {
console.log(err);
return res.redirect('/students');
}
res.render('pages/students/show', { student : foundStudent });
});
});
How can I get it to know that that id no longer exists?
Upvotes: 1
Views: 60
Reputation: 4922
send to show only if student is found. according to your logic if there is no error it will got to 'show' as not found is not error so it will goto show.
router.get('/:id', function(req, res) {
Student.findById(req.params.id, function(err, foundStudent) {
if(err) {
console.log(err);
return res.redirect('/students');
}
if(foundStudent){
res.render('pages/students/show', { student : foundStudent });
}
return res.redirect('/students');
});
});
Upvotes: 3