Home > Net >  how to do relationships in node js
how to do relationships in node js

Time:04-20

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);

CodePudding user response:

import { model, Schema } from "mongoose";

const bookSchema = new Schema({
  // ...
})

model("Book", bookSchema) // <-- if this line doesn't exist mongoose will treat books as an embedded array in authorSchema, this line ensures its treated as a collection
export default bookSchema;
import { model, Schema } from "mongoose";
import bookSchema from './bookSchema'

const authorSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    maxlength: 50,
  },
  books: [bookSchema], // <-- tells mongoose this is either a collection or embedded set of records, the way you had it defined told mongoose that there was only (1) book
});

model("Author", authorSchema)
export default authorSchema;

as far as I know you do not need to export model declarations, the declaration initializes the collection in mongodb, you do need to export the schema though wherever its being used in external files, so books need to be exported in order to be used in author. The error you encountered is because you declared your model in such a way to only support one book per author

  • Related