javascriptnode.jsmongodbmongooseejs

Mongoose findByIdAndRemove() function doesn't seem to work?


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.sstatic.net/ujL7Z.png

But 'Test' is still intact: https://i.sstatic.net/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.


Solution

  • 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("/");
    });