Using Mongoose with Next.js to implement CRUD operations

I have been successful in implementing POST and GET methods in my Next.js app using mongoose, but I am facing challenges with the delete operation.

This is an example of my POST method located in the API folder:

export default async function addUser(req, res) {
 const data = req.body
 await connectDB()
 const myDocument = await userModel.create(data)
 res.json({ myDocument })
}

Below is how I called it from the frontend:

async function Login(e) {
  e.preventDefault()

  const userObject = {
    user_name: userName,
    password: password
  }

  const response = await fetch('/api/add', {
    method: 'POST',
    body: JSON.stringify(userObject),
    headers: {
      'Content-Type': 'application/json'
    }
  })

  const data = await response.json()
  console.log(data)
}

I was able to retrieve the data using this method and parse it through props for mapping:

export const getServerSideProps = async () => {
  await connectDB()

  const myDocument = await userModel.find()

  return {
    props: {
      myDocument: JSON.parse(JSON.stringify(myDocument))
    }
  }
}

How can I implement the DELETE method?

I attempted the following approach:

export default async function Remove(req, res) {
  await connectDB()
  await userModel.deleteOne({_id: req.params.id}, function (err) {
    if (err) {
      console.log(err)
    }
    res.send("Deleted")
  })
}

This is a method that typically works with Node.js and Express, but it seems to be ineffective here.

Here is the frontend function I tried:

function Delete(_id) {
  fetch(`/api/remove/${_id}`)
    .then(() => {
      window.location.reload()
    })
}

However, this solution is not functioning as expected.

Answer №1

After conducting extensive research, I finally devised a solution. I implemented a dynamic route in my "API" directory named "[id].js" and inserted the following code:

export default async (req, res) => {
const {query: {id}} = req
await connectDB()
const deletedUser = await userModel.findByIdAndDelete(id)
if (!deletedUser) return res.status(404).json({msg: "does not exist"})
return res.status(200).json()}

I made adjustments to my front-end as follows:

async function Delete(_id) {
    await fetch(`/api/${_id}`, {
        method: 'DELETE'
    }).then(() => {
        //Perform tasks here
    })
}

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

Mastering the art of jQuery UI development, similar to the techniques

I'm currently working on creating an abstraction layer for jQuery UI that enables the definition of Widgets as Objects, similar to ExtJS. Here's how it works: var mydialog = new $.ui.dialog({ modal:true, renderTo:'body', title:'T ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...

Issue: My application is unable to start due to the module nuxt.js not being found. Can someone help me troubleshoot

Upon attempting to execute npm run dev following the installation of dependencies, I encountered an error that has left me puzzled. Despite trying various solutions found online, none have seemed to resolve the issue. <a href="/cdn-cgi/l/email-protectio ...

Guide on displaying multiple views along with their respective models fetched through AJAX in Backbone

Hey there! I'm currently working on painting a screen with multiple models and associated views in backbone. To achieve this, I have separate ajax calls to fetch data for these views. Initially, I thought using the jQuery function $when(ajaxcall1, aja ...

The getServerSession() method in NextAuth fails to retrieve all of the user fields when called in an API route

I am currently working on implementing an API route where I need to verify the user's authentication status and check if they are an admin. As part of this process, I attempted to utilize the getServerSession method, however, it returned a session wit ...

The incorrect value of variable V is being passed to the doSomethingWithData(v) function. This could lead to unexpected results

const Greetings = () => { const [num, setNum] = React.useState(1); React.useEffect(() => { setTimeout(async () => { await setNum(2); processData(num) }, 3000) }, []); retur ...

Utilizing Threejs to implement dynamic text labels

Recently, after reading a discussion on stackoverflow, I decided to incorporate labels into my canvas. To achieve this, I created a second scene and camera to overlay the labels on top of the first scene. this.sceneOrtho = new THREE.Scene();//for labels t ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

AJAX jQuery requests can flatten arrays when they are sent

The below code shows an endpoint written in Express, using the body-parser middleware. app.post("/api/poll/new",api.NewPoll); api.NewPoll = function(req,res){ if(!req.body) return res.status(400).send("MISSING BODY"); console.log(req.body,typeof(r ...

When certain triggers are activated, a hidden textbox revealed through javascript is made visible

After changing a dropdown value (from ddlSource) and hiding some text boxes using JavaScript, everything works fine. However, when the user enters a certain value in another textbox triggering an AJAX call to populate some labels, upon form reload, the hid ...

Unchecked checkbox displays as checked in UI

I am facing an issue with checking checkboxes using JavaScript. Even though the checkbox appears to be checked in the program, it does not reflect the updates on the user interface. If anyone has a solution for this, please share. <!DOCTYPE html> ...

When selecting the top edge in React flow, it will automatically select the bottom

Documentation: Example from documentation: Steps to replicate issue: Drag and drop any node to a different location Select the top edge handle of the moved node Try dragging the edge out and notice that the bottom edge gets selected instead of the top e ...

Where can content-tag and main-tag be found in vue-virtual-scroller?

I've been trying to wrap my head around the vue virtual scroller. I couldn't help but notice in the demo that it utilizes a few HTML attributes... <virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

Converting a functional component into a class-based component

I am in the process of converting a functional based Component to a class-based Component and creating a PrivateAuth Component. Here is the original PrivateAuth functional Component. function PrivateRoute({ component: Component, ...rest }) { return ( ...

The proper way to utilize vue-material's tab router alongside vue-router

Exploring the usage of vue-material tabs in my Vue project for navigation, I discovered that the standard tabs provided already offer this functionality (). However, I'm struggling to integrate these tabs with the normal vue router in my current setup ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

The Next.js API is indicating that the API request was resolved without a response being sent, however, I am confident that I

After creating a basic page and API for uploading a CSV file, I encountered an issue. The file uploads successfully and gets saved on the server through the API, but an error message pops up: API resolved without sending a response for /api/uploadv2, this ...

Identifying the presence of a particular cookie

I'm currently working on a project that already has several cookies stored. My goal is to determine if the cookie labeled "login" exists. Below is the code snippet I am using: if (document.cookie.indexOf("login") >= 0) { alert("login cookie ex ...