-2

When checking the checkbox with a /POST method to the server, it passes the item's ID back to the script.

Then I try to call the findByIdAndRemove() function but it doesn't seem to actually delete the document.

I'm checking with Mongosh (MongoDB new Shell).

NODE:

app.post('/delete', function(req, res){

  const checkedItem = req.body.checked;

  Item.findByIdAndRemove(checked);
  
});

EJS:

<% newListItems.forEach(function(item){ %>

      <form action="/delete" method="post">

        <div class="item">
          <input type="checkbox" onChange="this.form.submit()" name='checked' value='<%= item._id %>'>
          <p> <%=item.name%> </p>
        </div>

      </form>


    <% }); %>

'Test' should be deleted when checked: https://i.stack.imgur.com/ujL7Z.png

But 'Test' is still intact: https://i.stack.imgur.com/vomkW.png

With the most recent Mongoose upgrade to version 7.0, they removed callbacks and some methods stoped working the way they did.

I've tried reading their docs about async and await, using .then and .catch and found no help on the open web since the update is recent.

Henry
  • 3
  • 2
  • Please include code in the question as formatted text, not as images. https://meta.stackoverflow.com/q/285551/2282634 – Joe Mar 22 '23 at 22:44
  • [_You should use findOneAndDelete() unless you have a good reason not to_](https://stackoverflow.com/a/54629175/283366) – Phil Mar 22 '23 at 22:55
  • 1) You should wait for the delete operation to complete. 2) Have you debugged the `req.body.checked` value to make sure it's correct? – Phil Mar 22 '23 at 22:56
  • Thanks Joe and Phil for the tips. Yes Phil, I have debugged the query, it works fine. This post: https://stackoverflow.com/questions/75586474/mongoose-stopped-accepting-callbacks-for-some-of-its-functions helped me, using try, catch and await and async the right way. – Henry Mar 23 '23 at 16:46

1 Answers1

1

I'm also facing the same problem so, I put everything under async function inside post request.

app.js

app.post("/delete", function(req,res){

async function myDelete(){
  const checkedItemId = req.body.checkbox;

  const del = await Item.findByIdAndRemove(checkedItemId);

};
myDelete();
res.redirect("/");
});
Ayush
  • 26
  • 1