Reputation: 45
I'm able to add and read from the database currently, but when I click the delete link I created in the view, I'm given an error "Cannot GET /destroy/".
Here's some my code:
var Person = require('.././schema.js');
var mongoose = require('mongoose');
exports.create = function(req, res) {
new Person({
empName: req.body.empName,
role: req.body.role,
wage: req.body.wage,
update: Date.now()
}).save(function(err, people){
people.details();
res.redirect('/');
});
};
exports.destroy = function(req, res) {
Person.findById( req.params.id, function ( err, people) {
people.remove( function( err, people) {
console.log("Destroyed: " + people + " successfully!");
res.redirect( '/' );
});
});
};
View:
<h3><%= title %></h3>
<blockquote>
<ul>
<% for(var i = 0; i < peopleList.length; i++) { %>
<li class="litext"><strong>Name:</strong> <%= peopleList[i].empName %><strong>Role:</strong> <%= peopleList[i].role %> <strong>Wage:</strong> <%= peopleList[i].wage %></li>
<span class="litext"><a href="/destroy/<%= peopleList._id %>" title="Delete Person">Delete</a></span>
<% }; %>
</ul>
</blockquote>
From app.js:
var port = process.env.port || 4000;
var express = require('express');
var bodyParser = require('body-parser');
var forms = require('./controllers/forms');
var mongoose = require('mongoose'); // for mongoDB
var Person = require('./schema.js'); // db schema
var app = express();
app.use('/public', express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.use(bodyParser());
app.get('/destroy/:id', forms.destroy);
app.post('/submit', forms.create);
I didn't include any code from the controllers, don't think that is necessary as I think the issue is with routing.
Upvotes: 0
Views: 579
Reputation: 10080
Looks like you are not passing the ID while calling the destroy method. Replace the below line:
<a href="/destroy/<%= peopleList._id %>
With
<a href="/destroy/<%= peopleList[i]._id %>"
Upvotes: 2