The Model.findOneAndRemove() method has been updated and can no longer accept a callback function, resulting in

const express = require('express')
const mongoose = require('mongoose')
var app = express()
var Data = require('./noteSchema')

mongoose.connect('mongodb://localhost/newDB')

mongoose.connection.once("open", () => {
    console.log("Connected to the database!")
}).on("error", (error) => {
    console.log("Failed to establish connection"+ error)
})
app.post("/create", (req,res) => {
    var note = new Data ({
        
        note: req.get("note"),
        title: req.get("title"),
        date: req.get("date")
    })

    note.save().then( () => {
        
        if( note.isNew == false){
            console.log("Data saved successfully!")
            res.send("Data saved successfully!")
        }else{
            console.log("Failed to save data!")
        }
    })
})
app.get('/fetch', (req, res) => {    
    Data.find({}).then( (DBitems) => {
        res.send(DBitems )
    })  
})
app.post("/delete" , ( req , res ) =>{
    Data.findOneAndDelete({
        _id: req.get("id")   
    })
    console.log("Deleted successfully!")
    res.send("Deleted!")
})
var server = app.listen (8081,"192.x.x.x",()=>{
    console.log("Server is up and running!")
}) 

I've attempted multiple solutions but I'm still unable to find the right one.

It appears that there have been some changes in the latest update.

Error message: MongooseError: Model.findOneAndDelete() no longer accepts a callback

Answer №1

When encountering the issue, simply update your code to utilize the async function as shown below:

app.post("/delete", async (req, res) => {
    await Data.findOneAndRemove({
        _id: req.get("id")   
    })
    res.send("Deleted!")
})

Answer №2

While the previous answer is accurate, it overlooks the error handling aspect that is crucial in callback functions. To address this, an improved version of the code can be implemented:

app.post('/remove', async (req,res) => {
  try {
    await  Data.findOneAndDelete({ _id: req.get("id") })
    res.send("Entry successfully deleted.")
  } catch(error) {   
    console.log("Deletion failed: " + error)
  }     
})

I hope this revised solution proves to be helpful :)

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

Storing sound recordings with GridFS

I am currently facing an issue with the following code, it is only working partially and I require assistance in fixing it. The function saveAudioToGridFS() should return a file ID to its calling function. Despite verifying that the value to be returned ...

The success callback is not triggered when making a JSONP request

I have a specific URL that returns JSON data when accessed through a browser or REST client. However, I am having trouble making the request using jQuery in my express server running over HTTPS. Despite receiving a successful response in the network debug ...

What's the issue with this HTML button not functioning properly?

I'm having an issue with a button in my code that is supposed to change the text from 'hello' to 'Goodbye', but for some reason, it's not working. I have ensured that my code is properly indented in my coding program. Below i ...

Encountering an issue with transmitting live data. Instead of dynamic content, only static data is appearing

Trying to figure out how to retrieve dynamic data in my React code. Currently, I can only get static data after posting "hello world" from the input field labeled "add new todo task." I want to gain more experience by practicing and understanding how to fe ...

filling out a form with data retrieved through an ajax request

After retrieving JSON data from an MVC controller, I am attempting to populate a form with this data but encountering difficulties. The returned data consists of only one row with three properties. Despite confirming that the data is being returned success ...

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

Retrieve the entire document in a MongoDB find query

Imagine I have the following document: { id: 1, name: "alex", adress: [ {type: "home" , street: "flower"}, {type: "business" , street: "falls"}, {type: "xxx" , street: "xxx"}, ] } I am trying to retrieve the home address from this doc ...

Obtain the distinct highest value for every vertical axis on a bar graph

I'm facing an issue with my code where I am appending multiple SVG elements and generating 3 different charts. The problem is that the maximum value evaluated from the y.domain() for each y-axis is taken as the maximum value from all of my data. Is t ...

How can I disable a select element in Laravel 5?

Hey everyone! Currently using Laravel 5 and trying to style the "select" class as "selectpicker". I'm facing an issue where I want to disable or hide the selected option when clicked, as I'm creating a div with the option's content right b ...

How to execute a JavaScript function within a Jinja for loop

I am currently working on an HTML page where the variable schedule contains a series of sequential decimal numbers representing seconds. My goal is to develop a function in JavaScript/jQuery that can convert these decimal numbers into time format. However ...

Puzzled on how to include a string in the parameter for a GET request?

Following the initial instruction to make a get request for a turtles route and send a JS object of turtles with their colors, I successfully implemented it like this: app.get('/turtles', function(req, res) { data = { Raphael: "Red", Le ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

Filtering data in Angular based on specific dates

Upon receiving data from an Angular service, I have a JSON object structured like this: [ { "id": 2, "order_status": "R", "order_date": "2015-09-12T07:58:24.733834Z", "update_timestamp": "2015-10-05T04:22:44.904227Z" ...

Using multiple main.js files with RequireJs in Play Framework 2.1.1 Java: A step-by-step guide

While working on a single-page app with AngularJs + RequireJs in Play Framework 2.1.1, I encountered an issue regarding the structure of my application. The project consists of two main sections - an admin dashboard and a normal website - both housed withi ...

Inquiries regarding scopes, node.js, and express

I struggle with understanding scopes and similar concepts in various programming languages. Currently, I am working on an express application where I take user input, query an arbitrary API, and display the results in the console. To interact with the REST ...

Error: Unable to locate module: Unable to locate '@material-ui/core/Container'

Encountering an error in the browser: Error message: Module not found: Can't resolve '@material-ui/core/Container' The search for the component is directed towards my components directory instead of node_modules. Unfortunately, changing ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Hero Sticky Transition with 100vhDivElement

My code is giving me some trouble. I want the div with text to stay at the bottom of the hero section with a transparent background. When that div reaches the top, it should stick with a black background. The issue is that I have set it in the javascript v ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...