如何在节点js中做关系

how to do relationships in node js

我正在尝试在两个集合(书籍集合和作者集合)之间建立关系。我有在作者和书籍中使用的获取功能和创建功能,但我无法使用更新和删除请求。

这是我的请求正文

{
    "name":"TestAuthor",
    "_id":"625cbc5bad86965c4e5ee104"
    
}

我是邮递员我收到这个错误

    {
        "msg": "E11000 duplicate key error collection: myFirstDatabase.books index: _id_ dup key: { _id: ObjectId('625cbc5bad86965c4e5ee104') }"
}

这里是我作者的更新函数

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",
    });
  }
};

以及删除功能

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",
    });
  }
};

以及我的作者路线以防万一,但我认为这不是问题所在。

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

作者模型

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

据我所知,您不需要导出模型声明,该声明会在 mongodb 中初始化集合,您确实需要导出模式,尽管它在外部文件中的任何地方使用,所以 books 需要导出才能在 author 中使用。您遇到的错误是因为您以仅支持每位作者一本书的方式声明您的模型