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.