Search code examples
node.jsmongodbexpresspug

Express JS does not perform delete


PUGJS script

form(id="form1" action="/delete" method="POST")
input(type="submit",name=+item['id'] value="delete")

My ExpressJS code

router.post('/delete', function(req, res, next) {
    var id = req.params("i");
    console.log("i am 0")
    MongoClient.connect(url, function(err, db) {
        console.log("i am 1")
        db.collection('books', function(err, book) {
            db.collection.deleteOne( {_id: new mongodb.ObjectID(id)} );
            console.log("i am 2")
            if (err) {
                throw err;
            } else {
                db.close();
                res.redirect('/');
            }
        });
    });
});

Trying to perform a delete request but it does not even print ("i am 0") can not determine what's broken with the code

NPM response POST /delete 404 7.247 ms - 1202


Solution

  • When you see a 404 the root cause is definitely how you set up the routing. This code would be successfully called if it is in app.js/server.js (or whatever your root express file is), but a 404 means that you have placed it in a secondary file and are using another path in there somewhere.

    With that said, you also have an issue with how your route is defined if you want to read a route parameter (which is what the first line of your route handler tries to do).

    router.post('/delete/:i', function...
    

    The form itself isn't passing any id though through name (or id). You could either pass the id through the url called:

    action= "/delete?id=" + id
    

    ...and read this in your route handler using req.query.id or you could insert a hidden input in the form and read it using req.body.id.

    Also, the form name attribute has been deprecated and should be replaced with id.

    Then, it's important to note that pug is highly dependent on indentation. Your code as pasted will generate an empty form and a separate input field.

    This:

    form(id="form1" action="/delete" method="POST")
    input(type="submit",name=+item['id'] value="delete")
    

    Generates this HTML:

    <form id="form1" action="/delete" method="POST"></form>
    <input type="submit" name="itemId" value="delete">
    

    If you change the pug template to this (note the two additional spaces on the input line):

    form(id="form1" action="/delete" method="POST")
      input(type="submit",name=+item['id'] value="delete")
    

    You will get this, which should work as expected:

    <form id="form1" action="/delete" method="POST">
      <input type="submit" name="itemId" value="delete">
    </form>
    

    Then, there's the problem in your delete function where you're missing a callback.

    db.collection.deleteOne( {_id: new mongodb.ObjectID(id)} );
    

    You need to either add a promise or callback here otherwise your code will move straight to close the connection.