I'm struggling with what should be a simple case, but I can't seem to get to the bottom of it: I am building a very simple CRUD app with nextjs using MongoDB.
I am following the official nextjs "with-mongodb-mongoose" as a guide (https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose)
While all should be simple, my code fails to properly create a document with the form data to be sent to MongoDB. In other words, all my entries in MongoDB are empty documents:
{ _id: new ObjectId("63a5aa1317a618f4d3eefab8"), __v: 0 }
Taking it to step by step:
- I have created a very simple model that only takes "name" as a paremeter:
import mongoose from 'mongoose'
const raceresultSchema = new mongoose.Schema({
name: String,
});
const Raceresult = mongoose.models.Raceresult || mongoose.model('Raceresult', raceresultSchema)
export default Raceresult
- My POSt API route is exactly the same as the one in the GitHub repo from nextjs:
case 'POST':
try {
const newResultDoc = await Raceresult.create(req.body);
res.status(201).json({ success: true, data: newResultDoc })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
- I use ThunderClient in VSCode to simplify, and I make a POST request to the right API route with the following body:
{
"name": "test"
}
- I systematically get the following answer:
{
"success": true,
"data": {
"_id": "63a5b71917a618f4d3eefae3",
"__v": 0
}
}
As I'm following the syntax from the Github repo, I don't see what I'm doing wrong.
The DB connection works fine. These empty documents get saved on my MongoDB, with no problem. When I add elements manually in MongoDB Atlas, that works fine and the items get saved properly, with no problem.
The problem happens whenever I try to use the API route to save a document. So I guess the problem must come from the API POST code or from the body format. However, I can't figure out what is wrong as I'm following the syntax from the official GitHub repo...
I have seen another StackOverflow post with a similar type of issue, but the solution did not seem applicable to my case.
Appreciate your help!
EDIT: I copy/pastd the code from the nextjs github repo (Pet model, and Pet API route) and made a POST request in Thunder Client to save a pet in my database (which is not the point) and... it worked, the document is saved in my database with the data from the req body... I'll keep trying and update this post if I succeed with my own model