简体   繁体   中英

DELETE Request with nodejs and Mongoose

I'm struggling to delete a row from a collection of my database using mongoose. The console said that deleting was successful (as I handled error), but when I check my database, the row is still here. I successfully add a member with a post request, but I was not able to delete it. I suspect my route file or my hbs file. Here is the code:

Index.js (the route part)

app.get('/delete',(req,res) => res.render('delete', {
    title:'Member App',
}));

routes/members.js

// Delete member : DELETE
router.get("/delete", (req,res)=>{
    console.log(req.params.id);
    Member.deleteOne({ _id: req.params.id }, function(err,data) {
        if (!err) {
            console.log(data);

                console.log("member successfully deleted")
        }
        else {
                console.log("error")
        }
    });
    res.redirect("/");
});

delete.hbs

<h1 class = "text-center mb-3">{{title}}</h1>
<form action="/delete" method ="DELETE" class="mb-4">
<div class="form-group">
    <label for="Id">Id</label>
    <input type="Id" name="Id" class ="form-control">
    
</div>
    

<input type="submit" value ="Delete member" class="btn">
</form>


The console: (it seems that the data from my callback is undefined)

Connected to mongoDB
undefined
{ n: 0, ok: 1, deletedCount: 0 }
member successfully deleted

Your input type tag is wrong.

<input type="Id" name="Id" class ="form-control">

There is no "Id" type in input (see input types values )

You don't use correct field

req.params.id

Is used, but I don't see any params in your request.

You only have the body filled with Id so in order to use it, you should call:

req.body.Id

First of all the absence of an error does not guarantee the deletion of a record in the database. So in this case prefer to use findOneAndRemove method.

Second res.redirect("/"); will called before record removing has done, so redirect should be moved into callback function like:

Member.findOneAndRemove({ _id: req.params.id }, function(err, member) {
    if (!err && member) {
        console.log(member);
        console.log("member successfully deleted")
    }
    else {
        console.log("error")
    }
    res.redirect("/");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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