简体   繁体   English

通过 ID 与 Express 的两个集合之间的 MongoDB 关系

[英]MongoDB relation between two collections by ID with the Express

I am facing a problem while making a relation between two collections (I am using MEAN stack) I have two collections: Books and Authors我在建立两个集合之间的关系时遇到问题(我正在使用 MEAN 堆栈)我有两个集合:书籍和作者

In frontend I want to make a CRUD menu, where I add a new book in the table and then from there i insert a few data about book and then I choose author from the dropdown menu (fetchin data from Authors collection)在前端,我想创建一个 CRUD 菜单,在表格中添加一本新书,然后从那里插入一些关于书的数据,然后从下拉菜单中选择作者(从 Authors 集合中获取数据)

So at the end my Book collection needs to have a few data about the book and then inside the object i need an array of data about those author.所以最后我的 Book 集合需要有一些关于这本书的数据,然后在对象内部我需要一个关于这些作者的数据数组。

Book schema:图书架构:

const BookSchema = new mongoose.Schema({
owner: { type: String, required: true },
pagesNo: { type: String, required: true },
releaseDate: { type: String, required: true }, 
country: { type: String, required: true },
authorID: { type: String, required: true }, <-- HERE I NEED DATA ABOUT AUTHOR
});

Author schema:作者架构:

  const AuthorSchema = new mongoose.Schema({
      name: { type: String, required: true },
      surname: { type: String, required: true },
      dateOfBirth: { type: String, required: true },
      countryOfBirth: { type: String, required: true },
      
    });

Book route: book.ts预订路线:book.ts

router.get("/", async (req, res) => {
  try {
    const books= await Book.find();

    let Author = await Author.find({
      books: { $elemMatch: { _id: books.bookID } },
    });

    res.status(200).json(books);
  } catch (err) {
    res.status(404).json({ success: false, msg: "Booknot found" });
  }
});

The problem is somewhere inside the find() function.. Is it even a good practice?问题出在 find() 函数内部的某个地方。这甚至是一个好习惯吗? I want that it can handle a lot of data.我希望它可以处理大量数据。

Thanks to everyone!谢谢大家! Greetings.问候。

Your Book schema would be like this:您的 Book 架构将是这样的:

const MongooseSchema = new mongoose.Schema({
  owner: {
    type: String,
    required: true,
  },
  pagesNo: {
    type: String,
    required: true,
  },
  releaseDate: {
    type: String,
    required: true,
  },
  country: {
    type: String,
    required: true,
  },
  authorId: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true,
  },
});

And your Author Schema would remain the same (in order to link both schemas).并且您的作者模式将保持不变(以便链接两个模式)。

Your route would be like this (if you want to search all books along with their author names):您的路线将是这样的(如果您想搜索所有书籍及其作者姓名):

router.get('/', async (req, res) => {
  try {
    const books = await Book.find().populate('authorId');

    res.status(200).json(books);
  } catch (err) {
    res.status(404).json({ success: false, msg: 'Booknot found' });
  }
});

And in case you want to search for books with a specific author id then your route would be like this:如果您想搜索具有特定作者 ID 的书籍,那么您的路线将是这样的:

router.get('/', async (req, res) => {
  try {
    const books = await Book.find({ authorId }).populate('authorId');

    res.status(200).json(books);
  } catch (err) {
    res.status(404).json({ success: false, msg: 'Booknot found' });
  }
});

AuthorID should be type ObjectId, not string. AuthorID 应该是 ObjectId 类型,而不是字符串。

To join data from other table, you have to use an aggregate with a lookup .要连接来自其他表的数据,您必须使用带有lookup聚合

let author = await Author.aggregate([
    {
        $lookup:
        {
            from: "books",
            localField: "_id",
            foreignField: "authorID",
            as: "books"
        }
    }
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM