I am more or less a beginner and I am having a real issue with a post request in my back end. I am trying to create a note object, which is always assigned to a user upon creation. The post request to create the user worked fine, and when I manually enter a note object into MongoDB, I can retrieve it with a GET request. Here is the code in question:
const createNewNote = asyncHandler(async (req, res) => {
const { user, title, text } = req.body;
if (!user || !title || !text) {
return res.status(400).json({ message: "All fields are required" });
}
const duplicate = await Note.findOne({ title }).lean().exec();
console.log("Duplicate: ", duplicate);
if (duplicate) {
return res.status(409).json({ message: "Duplicate note title" });
}
const noteObject = { user, title, text };
console.log("Note object: ", noteObject);
const note = await Note.create(noteObject);
console.log("New note: ", note);
if (note) {
res.status(201).json({ message: `New note ${title} created.` });
} else res.status(400).json({ message: "Invalid note data received." });
});
The console.logs are showing everything as they should. Here is what I have been putting into Postman in the request body:
{
"user": "64ef1676195cb3604dafea89",
"title": "Hello again",
"text": "This is also a note."
}
This is the Note.model.js:
const mongoose = require("mongoose");
const AutoIncrement = require("mongoose-sequence")(mongoose);
const noteSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
title: {
type: String,
required: true,
},
text: {
type: String,
required: true,
},
completed: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
noteSchema.plugin(AutoIncrement, {
inc_field: "ticket",
id: "ticketNums",
start_seq: 500,
})
module.exports = mongoose.model("Note", noteSchema);
This is the noteRoutes.js file:
const express = require("express");
const router = express.Router();
const notesController = require("../controllers/notesController");
router
.route("/")
.get(notesController.getAllNotes)
.post(notesController.createNewNote)
.patch(notesController.updateNote)
.delete(notesController.deleteNote);
module.exports = router;
I really don't know what to do at this point, my console indicates that the connection to mongoDB is up and running, and all requests on the user controller are working perfectly.
I have tried logging the console, I have tried using thundercat as well as postman, I have tried updating dependencies and removing other parts of code that may affect this. I am not experienced so I don't really know what troubleshooting steps I should take next,