简体   繁体   中英

Express MongoDB, & Mongoose DELETE with findByIdAndRemove() then redirect

I'm currently trying to use a DELETE method however it seems like the res.redirect isn't triggering.

As you can see I am trying to delete a record in MongoDB using findByIdAndRemove():

  app.delete("/car", (req, res) => {
    Car.findByIdAndRemove(req.body.id, (err, car) => {
      res.redirect('/');
    });
  });

When I send a DELETE request through Postman with the id the server doesn't respond and appears to hang.

Any idea why this might be happening? I'd like it to delete the record with the id past and then redirect to the homepage.

Thanks

You have to handle the error returned by mongodb, if the query throw error or req.body.id is undefined the page will hangs because you didn't terminate the request/response cycle by sending a response to clients, here is an example:

app.delete("/car", (req, res) => {

    Car.findByIdAndRemove(req.body.id, (err, car) => {

        // check if query error
        if (err) {
            console.log(err);
            return res.json({ success: false });
        }

        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