我想在兩個收藏之間建立關系——一本書和作者收藏。如果我只使用獲取并顯示我的所有書籍并通過 id 集成有關作者的資料,它就可以作業。
作者架構:
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 },
});
圖書架構:
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: Schema.Types.ObjectId, ref: "Author", required: true }, <-- HERE I NEED DATA ABOUT AUTHOR
});
我的用于獲取所有資料的快速函式:
router.get("/", async (req, res) => {
try {
let books = await Book.aggregate([
{
$lookup: {
from: "authors",
localField: "authorID",
foreignField: "_id",
as: "author",
},
},
]);
res.status(200).json(books);
} catch (err) {
res.status(404).json({ success: false, msg: "Book is not found" });
}
});
但是現在,當我按 ID (findById()) 搜索一本書時,我也想顯示該連接資料。如果我使用這樣的函式,我會得到一個錯誤狀態:
router.get("/:bookId", async (req, res) => {
try {
let book= await Book.aggregate([
{
$lookup: {
from: "authors",
localField: "authorID",
foreignField: "_id",
as: "author",
},
},
]);
book= book.findById({ _id: req.params.bookId});
res.status(200).json(book);
} catch (err) {
res.status(404).json({ success: false, msg: "Book is not found" });
}
});
感謝您的幫助
uj5u.com熱心網友回復:
使用 $match 僅查找同一查詢的一本書
const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId();
router.get("/:bookId", async (req, res) => {
try {
let book= await Book.aggregate([
{
$match: { _id : ObjectId("book _id") }
},
{
$lookup: {
from: "authors",
localField: "authorID",
foreignField: "_id",
as: "author",
},
},
]);
book= book.findById({ _id: req.params.bookId});
res.status(200).json(book);
} catch (err) {
res.status(404).json({ success: false, msg: "Book is not found" });
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/478713.html
