Im做上的NodeJS和MongoDB,但即时通讯卡上的DELETE方法一个RESTful服务器中删除,因为我尝试了req.body.listId铸成时收到错误HTTP使用的NodeJS和MongoDB
"Argument passed in must be a single String of …modules\express\lib\router\index.js:174:3"
的ObjectId。
这里是我的代码:
router.delete('/', function(req, res){
var db = req.db;
var collection = db.get('listcollection');
var oId = new ObjectId(req.body.listId); //The exception is here
collection.remove(
{
"_id": oId
},function(err,doc){
if (err) {
res.json("There was a problem deleting the information to the database.");
}
else {
res.json("Successfully deleted");
}
}
);
});
解决!: 的listId参数被引述( “58f8b2cc8cf726ca76551589”),所以我做了一个切片。无论如何,我改变了在URL中收到的参数,下面是代码:谢谢!
router.delete('/:listId', function(req, res){
var db = req.db;
var collection = db.get('listcollection');
var listId = req.params.listId;
listId = listId.slice(1, listId.length - 1);
var oId = new ObjectId(listId);
collection.remove(
{
"_id": oId
},function(err,doc){
if (err) {
res.json("There was a problem deleting the information to the database.");
}
else {
res.json("Successfully deleted");
}
}
);
});
删除方法的参数只能通过查询字符串/ URL本身传递,而不是像post或put –
您能告诉我们您的请求身体是什么样子吗?你发布了什么?这听起来像'req.body.listId'的内容违反了'ObjectId'的限制。此外,如前所述,在URL中指定id会更加RESTful,因此您的路由将变成'router('/:id')',然后您可以通过'req.params以快速方式访问id。 id'。 – benjiman
listId参数被引用(“58f8b2cc8cf726ca76551589”),所以我做了一个切片。无论如何,我改变了在URL中收到的参数。谢谢! –