【发布时间】:2016-06-28 16:25:35
【问题描述】:
我正在使用 MEAN 堆栈和 sequelize。我有两种情况想从表中删除记录:
1) 使用给定的 id 删除一条记录。
2) 删除满足某些条件的所有记录(共享一个 projectId 的所有记录)。为此,我尝试设置两条路线来处理每种情况。
客户端服务(案例一):
this.deleteCampaign = function(id) {
return $http.delete(campaignBaseUrl + id);
};
客户端服务(案例2):
this.deleteMultipleCampaigns = function(projectID) {
return $http.delete(campaignBaseUrl+ 'foo/' + projectID);
};
服务器端路由:
// I want case 1 to access this route (working)
router.delete('/:id', controller.destroy);
// I want case 2 to access this route (not working)
router.delete('/foo/:projectID', controller.destroyMultiple);
更新 服务器端控制器:
// Deletes multiple Campaign from the DB
// for a give project ID
export function destroyMultiple(req, res) {
console.log('req.params:');
console.log(req.params); // { projectID: '7' }
Campaign.findAll({
where: {
projectId: req.params.projectID
}
})
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
}
// Deletes a single Campaign from the DB
export function destroy(req, res) {
console.log('destroySingle:');
Campaign.find({
where: {
_id: req.params.id
}
})
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
}
更新 2
服务器端控制器继续...
function removeEntity(res) {
return function(entity) {
if (entity) {
return entity.destroy()
.then(() => {
res.status(204).end();
});
}
};
}
当我从客户端运行 case2 时,我收到此错误:
DELETE /api/campaigns/foo/7 500
和
{"name":"SequelizeDatabaseError","message":"invalid input syntax for integer: \"foo\"","parent":
【问题讨论】:
-
也许 'foo' 被传递到您的数据库查询而不是 58。
destroyMultiple如何解压参数? -
我也是这么想的,用这个来检查id参数:
router.param('id', function (req, res, next, id) { console.log('id:'); console.log(id); next(); });id是正确传递的 -
您确定为该请求调用了正确的处理程序(即
destroyMultiple)吗? -
它应该是
projectID而不是id所以也许它实际上是在调用 :id 路由。 -
@leetibbett 我不确定我是否理解,
projectId和id都是整数,它们如何确定路由?
标签: javascript express sequelize.js