NodeJS / Mongoose / Express - 无法在单击时从db中删除项目

时间:2015-12-18 01:25:12

标签: node.js mongodb express mongoose ejs

我当前可以添加和读取数据库,但当我单击我在视图中创建的删除链接时,我收到错误“无法获取/销毁/”。

这是我的一些代码:

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( '/' );
});
});
};

查看:

<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>

来自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);

我没有包含来自控制器的任何代码,不认为这是必要的,因为我认为问题在于路由。

1 个答案:

答案 0 :(得分:1)

看起来你在调用destroy方法时没有传递ID。替换以下行:

<a href="/destroy/<%= peopleList._id %>

使用

<a href="/destroy/<%= peopleList[i]._id %>"