MongoDb通过传递用户ID删除文档 [英] MongoDb delete documents by passing user id

查看:94
本文介绍了MongoDb通过传递用户ID删除文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node和mongo db的新手.我在每行中都有一个带有删除链接的用户列表.我正在尝试删除其 _id 的用户.但是它不起作用. 这是我的路由器代码.

I am new to node and mongo db. I have a list of users with delete link in each row.I am trying to delete a user with its _id. However its not working. Here is my router code.

router.get('/delete/:id', function (req,res) {
    const ObjectId = require('mongodb').ObjectID;
    var id = req.params.id;
    console.log(id);
    db.collection('users').deleteOne({ _id: ObjectId(req.params.id) }, function(err, res) {
        if (err) {
        throw err;
        } else {
          return res.redirect('/'); 
        }
      });

  });

这是我的观点,单击此链接后,我在URL中获得的_id如下: http://localhost:3000/delete/4428439e14e3343ba4ac31c1

Here is my view, on clicking this link I am getting the _id in my url as this : http://localhost:3000/delete/4428439e14e3343ba4ac31c1

<td><a href="/delete/ <%=  userdetails._id %>">Delete</a></td> 

console.log(id)给我4428439e14e3343ba4ac31c1

console.log(id) gives me 4428439e14e3343ba4ac31c1

但这会引发以下错误

错误:传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串 使用新的ObjectID

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters at new ObjectID

推荐答案

尝试一下,如果字符串是有效的ObjectID

Try this, you don't need to create ObjectID if the string is a valid ObjectID

为预防起见,您可以使用下面的函数来测试是否通过了有效的ObjectID

For prevention, you can use a function like below to test if valid ObjectID is passed or not

function validateObjectId (id) {
    if (ObjectId.isValid(id)) {
        const obj = new ObjectId(id);
        if (obj == id) {
            return true;
        }
    }
    return false;
},


if(!validateObjectId(req.params.id))
    return res.send({'error':'Invalid ObjectID Passed',id:req.params.id});

db.collection('users').deleteOne({ _id: ObjectId(req.params.id) }, function(err, res) 
{
    if (err) {
    throw err;
    } else {
      return res.redirect('/'); 
    }
  });

也请从此处删除多余的空间

Also remove extra space from here

<td><a href="/delete/<%=userdetails._id%>">Delete</a></td> 

这篇关于MongoDb通过传递用户ID删除文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆