The method Model.findByIdAndRemove() no longer supports using a callback function

I encountered an issue when attempting to check the checkbox on my to do list. An error message popped up saying "Model.findByIdAndRemove() no longer accepts a callback".

My goal is to have checked items automatically removed from the to do list.

app.post("/delete", function (req, res) {
  const checkedItemId = req.body.checkbox;
  Item.findByIdAndRemove(checkedItemId, function (err) {
    if (!err) {
      console.log("Successfully deleted checked item");
      res.redirect("/");
    }
  });
});

Answer №1

To tackle this issue, one can employ the async/await design pattern along with the findByIdAndDelete method as shown below:

app.post("/delete", async (req, res) => { //< Utilizing async and arrow function
   try { //< Implementing a try/catch block for improved error handling
      const checkedItemId = req.body.checkbox;
      const deletedItem = await Item.findByIdAndDelete(checkedItemId); //< Using await keyword
      console.log("Successfully deleted checked item:", deletedItem);
      res.redirect("/");
   } catch(err){
      console.log('Error:', err);
      //Sending error message to front-end
   }
});

The utilization of the findByIdAndDelete method triggers the findOneAndDelete middleware, which offers various useful options. Refer to the documentation here for more details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to transferring the current date to a text box using Angular JS with Protractor

I need to add a date field that is in text type. The HTML code for it is as follows: <input class="form-control ng-pristine ng-invalid ng-touched" type="text" id="date" name="date"> Can anyone assist me in automatically sending the current date to ...

Are Java's Streams comparable to JavaScript's Arrays?

Attempting to create a JavaScript equivalent for Java's IntStream.range(0, 5).forEach(System.err::println);, I have come up with the following: const IntStream = (function () { function range(start, end, numbers = []) { if (start === end) ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

Delete all embedded documents within a collection

I am attempting to eliminate all nested documents, not just one. Here is the provided code snippet: // Here we are searching for and deleting all embedded work order units db.workorders.find({units: { $ne: null } }, function(err, wos) { c ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

What is the best way for Cucumber to move on to the next annotation only after ensuring all async requests from the previous one have finished processing?

I am looking to set up a basic test using Selenium and Cucumber for logging into my web application and confirming that the main page is displayed correctly. Currently, all three tests are returning true even before the page is fully loaded. The issue ar ...

The ajax success response transforms when using @html.raw

In my Razor viewpage, I have the following jQuery code: $(document).ready(function () { var listValues = @Html.Raw(Json.Encode(Session["list"])); $("#nsline").click(function () { alert(listValues) $.ajax({ type: "P ...

Struggling to make addClass and removeClass function correctly for the development of the unique "15 puzzle" game

I am currently in the process of creating a version of "the 15 game" using jQuery in HTML. You can find more information about the game on this page. The objective of the game is to rearrange a table of "boxes" in ascending order from 1 to 15. Below is th ...

Require.js still loads modules in their uncompressed state even after the optimization process

I've successfully run the r.js optimizer and everything seems to be working fine. However, I am facing an issue where the compressed optimized version loads along with all the uncompressed modules. Any idea why this might be happening? build.js { a ...

Deactivating an asp.net label using client-side scripting

Having a web form with numerous controls and a submit button can be tricky. The issue arises when a user initially submits clean data, resulting in the display of a "form submitted successfully" message using an asp.net label control. However, if the same ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

What could be the reason behind my Discord bot never being marked as ready?

I'm currently working on developing a Discord bot using discord.js, but I've encountered an issue. The bot is never getting ready because it's not logging anything in the console. Here's the script snippet I'm using: import Discord ...

Generating a variety of modes from an array

My challenge is finding multiple modes from an array, but my code currently prints the modes multiple times. I specifically want to create an array with only 7 and 8 like this [7, 8] instead of [7, 7, 7, 7, 7, 8, 8, 8, 8, 8]. Can someone please assist me i ...

Combining two arrays by checking 2 specific fields in MongoDB to create a single array

I am currently working with a data collection: { _id:"123", obj1:[{defaultNo:1,fine:100},{defaultNo:3,fine:10}], obj2:[{default:1},{default:2},{default:3}] } Although I attempted a solution, I encountered a roadblock: db.collection.aggregate([ // Match ...

After resizing the window in jQuery, the scroll to section functionality does not behave as anticipated

My scroll function is not working properly after window resize. Here's how I want it to work: I resize the window. After resizing, when I click a specific menu item, the window should scroll to the section corresponding to that item with an offs ...

Load a PHP file through AJAX when the site is initially loaded

I have a PHP file that retrieves the latest 100 images from a directory. I set up a script to automatically reload the PHP file so we can utilize the data with JavaScript. The issue is that we only receive the information after the PHP file has been reloa ...

When clicking, the drop-down feature is malfunctioning as all the menus are dropping down simultaneously

I have been trying to implement a dropdown on click feature for my website, but it is not functioning as intended. () When I click on button 1, button 2 also drops down unexpectedly. This behavior is not desired. Below is the code snippet from the page: ...

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...