我在NodeJS和MongoDB上做一个RESTful服务器,但我坚持使用DELETE方法,因为我得到了错误
"Argument passed in must be a single String of …modules\express\lib\router\index.js:174:3"
尝试将req.body.listId强制转换为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");
}
}
);
});
答案 0 :(得分:0)
发生错误是因为req.body.listId
不符合ObjectId
规则 - ObjectId是一个12字节的字符串(24个0-9
或a-f
字符,例如{{ 1}})。可能出现的问题是:
"507f1f77bcf86cd799439011"
是普通数字,不是字符串类型,例如req.body.listId
。89876
是一个字符串,但不遵循上述规则。虽然它不是RESTful,但使用JSON正文的HTTP req.body.listId
请求完全没问题。 Node.js服务器可以接收请求及其正文。