NodeJS和MongoDB -使用aggregate和$lookup与findById



我想在两个集合之间建立一个关系——一本书和作者集合。如果我只使用获取和显示我所有的书,并通过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
});

我的express函数,用于获取所有数据:

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

谢谢你的帮助

使用$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" });
}
});

最新更新