我在建立兩個集合之間的關系時遇到問題(我正在使用 MEAN 堆疊)我有兩個集合:書籍和作者
在前端,我想創建一個 CRUD 選單,在表格中添加一本新書,然后從那里插入一些關于書的資料,然后從下拉選單中選擇作者(從 Authors 集合中獲取資料)
所以最后我的 Book 集合需要有一些關于這本書的資料,然后在物件內部我需要一個關于這些作者的資料陣列。
圖書架構:
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
});
作者架構:
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.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" });
}
});
問題出在 find() 函式內部的某個地方。這甚至是一個好習慣嗎?我希望它可以處理大量資料。
謝謝大家!問候。
uj5u.com熱心網友回復:
您的 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,
},
});
并且您的作者模式將保持不變(以便鏈接兩個模式)。
您的路線將是這樣的(如果您想搜索所有書籍及其作者姓名):
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' });
}
});
如果您想搜索具有特定作者 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' });
}
});
uj5u.com熱心網友回復:
AuthorID 應該是 ObjectId 型別,而不是字串。
要連接來自其他表的資料,您必須使用帶有lookup的聚合。
let author = await Author.aggregate([
{
$lookup:
{
from: "books",
localField: "_id",
foreignField: "authorID",
as: "books"
}
}
]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477722.html
上一篇:逐步選擇排序的mongodb檔案
