I am trying to make a relationship between two collections a books collection and an author collection. I have got the get function and create function working in authors and books but I can't get the update and delete requests to work.
here is my request body
{
"name":"TestAuthor",
"_id":"625cbc5bad86965c4e5ee104"
}
I postman I get this error
{
"msg": "E11000 duplicate key error collection: myFirstDatabase.books index: _id_ dup key: { _id: ObjectId('625cbc5bad86965c4e5ee104') }"
}
here is my author's update function
const updateAuthor = async (req, res) => {
try {
const { id } = req.params;
const author = await Author.findByIdAndUpdate(id, req.body);
if (!author) {
return res.status(404).json({
success: false,
msg: `No author with the id ${id}`,
});
}
const newAuthors = await Book.find({});
return res.status(200).json({ success: true, data: newBook });
} catch (err) {
return res.status(500).json({
msg: err.message || "Something went wrong while updating an Author",
});
}
};
And the Delete function
const deleteAuthor = async (req, res) => {
try {
const { id } = req.params;
const author = await Author.findByIdAndRemove(id);
if (!author) {
return res.status(404).json({
success: false,
msg: `No Author with the id ${id}`,
});
}
const newAuthors = await Author.find({});
return res.status(200).json({ success: true, data: newAuthors });
} catch (err) {
return res.status(500).json({
msg: err.message || "Something went wrong while deleting an Author",
});
}
};
and my routes for authors just in case but I don't think that is the issue.
import { Router } from "express";
const router = Router(); // Accessing the Router() object from express. This allows to handle various requests
// Importing the four functions
import {
getAuthors,
createAuthor,
updateAuthor,
deleteAuthor,
} from "../controllers/authors.js";
// Four routes that are mapped to the functions above
router.route("/").get(getAuthors);
router.route("/").post(createAuthor);
router.route("/:id").put(updateAuthor);
router.route("/:id").delete(deleteAuthor);
export default router; // You do not need to enclose router in curly braces
authors model
import mongoose from "mongoose";
const authorsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
maxlength: 50,
},
books: {
type: mongoose.Schema.Types.ObjectId,
ref: "Book",
},
});
export default mongoose.model("Author", authorsSchema);