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

Tips for navigating libraries with Google CAJA

Is there a way to configure Google Caja to allow specific libraries to work without being sanitized? I have my own CAJA server and an application based on NodeJS. I'm providing users with code that is mostly related to charts and graphs, but certain ...

Is it necessary to create event objects before setting event handlers in Leaflet JS?

I'm currently working on creating event handlers that respond to the success of the location() method in the leaflet JavaScript map class Here is my current implementation: function initializeMap() { var map = L.map('map').locate({setV ...

The deployment on Vercel is encountering an issue because it cannot find the React Icons module, even though it has been successfully installed

My attempt to deploy a project on Vercel is encountering an error during the building phase. The error message states that React icons cannot be found, even though they are installed in the package.json file and imported correctly in the component using th ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

In Next.Js 14, there seems to be an issue with the Shadcn.ui popover element commands where users are unable to select or click on the elements using

Currently, I am assessing the user-friendliness of the shadcn.ui component library in order to implement a popover component. Here is my attempt: import { Button } from "@/components/ui/button"; import { Command, CommandEmpty, CommandGroup, Comma ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

The function Server.listeners is not recognized by the system

Currently, I am following a tutorial on websockets to understand how to incorporate Socket.IO into my Angular project. Despite meticulously adhering to the instructions provided, I encountered an error when attempting to run my websockets server project: ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way: function (Vue, options) { Vue.$detector = new TranslatableStringDetector(); } Utilizing it within a computed property in my component is done l ...

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

Wiki experiencing issues with NodeJS HttpGet functionality

Goal Retrieve the HTML content of a Wiki Page. Introduction In an attempt to fetch the HTML of a Wiki page () for data parsing purposes, I am utilizing NodeJS and its HTTP Request methods. Code Snippet Below is the simple code snippet that accesses th ...

Embracing Error Handling with ES6 Promises

I am seeking clarification on how errors travel through a series of then continuations to a catch continuation. Consider the following code: Promise.reject(new Error("some error")) .then(v => v + 5) .then(v => v + 15) .catch(er ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

Issue with Mongoose: Struggling to perform upsert operation within a loop

I need assistance with upserting a document in a specific way. for (var i = 0; i < req.body.app_events.length; i++ ) { console.log(req.body.app_events[i].event_key); //delete upsertData._id; Appusers.update({app_key: req.body.app_key, e_key ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

I'm attempting to insert a line break after HTML elements that are being added from JavaScript code inside a `display: flex` div

I'm facing an issue where line breaks are not added after HTML elements are inserted via JavaScript upon clicking a button. For instance, the data from the inputs doesn't get separated even when I click submit multiple times: To illustrate, her ...