简体   繁体   English

从Express,Node.js应用程序中删除MongoDB文档

[英]Delete MongoDB document from Express, Node.js app

My index.jade file(my button which the users clicks to delete the document) is: 我的index.jade文件(用户单击以删除文档的按钮)是:

a(href="/delete/#{booking.id}") Delete

So far in my index.js file is: 到目前为止,我的index.js文件是:

router.get('/delete/:id', function (req, res) {
  Booking.findOneAndDelete({ id: req.params.id }).remove().exec();
});

I also, tried: 我也尝试过:

router.get('/delete/:id', function (req, res) {
  Booking.findById(id, function (err, doc) {
  if (err) {
    message.type = 'Error!';
  }
  doc.remove(callback); //Removes the document
  });

Neither are working, I just get the url with the ID: 两者都没有工作,我只是得到ID的URL:

localhost:3000/delete/54d49430b08883dc2fc8bb0d 本地主机:3000 /删除/ 54d49430b08883dc2fc8bb0d

You need to execute before you can remove, you should also be performing a delete request and not a .get(). 您需要在删除之前执行,您还应该执行删除请求而不是.get()。 Try this: 尝试这个:

router.delete('/delete/:id', function (req, res) {
    Booking.findById(req.params.id)
        .exec(function(err, doc) {
            if (err || !doc) {
                res.statusCode = 404;
                res.send({});
            } else {
                doc.remove(function(err) {
                    if (err) {
                        res.statusCode = 403;
                        res.send(err);
                    } else {
                        res.send({});
                    }
                });
            }
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM