I am using Postman to test deleting a document on Mongodb atlas in a NextJs 14.2.4application using the api router.
This is the route:
import { connectToMongoDB } from "@/app/lib/db";import Employee from "@/models/employee";import { NextResponse } from "next/server";import mongoose from "mongoose";export async function DELETE(request) { const id = request.nextUrl.searchParams.get("id"); console.log('id: ', id); console.log('id type: ', typeof id); if (!id) { return NextResponse.json({ message: "Employee ID is required" }, { status: 400 }); } if (!mongoose.Types.ObjectId.isValid(id)) { return NextResponse.json({ message: "Invalid employee ID" }, { status: 400 }); } try { await connectToMongoDB(); console.log("MongoDB connected successfully"); const deletedEmployee = await Employee.findByIdAndDelete(id); if (deletedEmployee) { return NextResponse.json({ message: "Employee deleted successfully" }, { status: 200 }); } else { return NextResponse.json({ message: "Employee not found" }, { status: 404 }); } } catch (error) { console.log("Error during deletion:", error); return NextResponse.json({ message: "An error occurred while deleting the employee" }, { status: 500 }); }}
This is the request url:
localhost:3000/api/employees?id=66972dc9f332a2f854b2cdc5
I have ensured that:
- Mongodb connection is open
- The object id param is valid
- The object id passed in the url matches the _id of a document in my collection
Without fail, this is what is logged on the console:
id: 66972dc9f332a2f854b2cdc5id type: stringConnecting to MongoDB...MongoDB connected successfullyMongoDB connected successfullyError during deletion: MongooseError: Operation `employees.findOneAndDelete()` buffering timed out after 10000ms at Timeout.<anonymous> (/Users/imarichildress/Documents/dev-projects/portfolio-new-2024/employee-mapping-app/vscode/employee-map-dashboard/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:23) at listOnTimeout (node:internal/timers:573:17) at process.processTimers (node:internal/timers:514:7) DELETE /api/employees?id=66972dc9f332a2f854b2cdc5 500 in 10869ms
This tells me that the client is communication with the server route. The failure seems to happening when I execute the findByIdAndDelete method.
I am trying to delete a document on my mongodb Atlas collection using Postman.
I am sure the connection to my db is open because
- My GET route to retrieve all documents works.
- My POST route to create a new document works.
I have ensured that:
- Mongodb connection is open
- The object id param is valid
- The object id passed in the url matches the _id of a document in my collection