[英]NodeJs, Mongoose find and populate works but aggregate, match and lookup doesn't
我的聚合有問題。我需要返回具有相同所有者 ID 的項目列表。 我作為查詢參數傳遞的所有者 ID。我已經嘗試了 $match 沒有 $in,
我嘗試將我的 id 轉換為 mongoose.Types.ObjectId (我的事件得到一個錯誤)。 但是我只完成了空的 object 作為回報..
exports.getContainersByOwner = async (req: Request, res: Response) => {
const { id }: any = req.query;
try {
const containers = await Container.aggregate([
{
$lookup: {
from: "containerstypes",
localField: "containerTypeID",
foreignField: "_id",
as: "containerTypes",
},
},
{
$lookup: {
from: "owners",
localField: "ownerId",
foreignField: "_id",
as: "owner",
},
},
{ $unwind: "$containerTypes" },
{ $unwind: "$owner" },
{ $match: { "owner._id": { $in: [id] } } },
]);
res.status(200).json(containers);
} catch (err) {
res.status(404).json({ success: false, msg: "Container not found" });
}
};
如果我從我的代碼 api 中刪除行 $match 會返回所有可以的項目,但我需要實現返回的項目具有相同的 id...我需要匹配彩色 id (owner._id)
容器的 model 是:
const ContainerSchema = new mongoose.Schema({
ownerId: { type: Schema.Types.ObjectId, ref: "Owners", required: true },
manufacturingNo: { type: String, required: true },
IdentificationNo: { type: String, required: true },
manufacturingDate: { type: Date, required: true },
nextInspectionDate: { type: Date, required: true },
certificateNo: { type: String, required: false },
containerTypeID: {
type: Schema.Types.ObjectId,
ref: "ContainersType",
required: true,
},
});
如果我使用這種方法它可以工作,但是 object 結構不正確,所以在前端有更多的變化要做.. 目前這是不可能的
try {
const containers = await Container.find({
ownerId: id,
})
.populate("containerTypeID")
.populate("ownerId");
res.status(200).json(containers);
} catch (err) {
res.status(404).json({ success: false, msg: "Container not found" });
}
您的$match
在邏輯上是錯誤的:
{ $match: { "owner._id": { $in: [id] } } }
由於id
本身是一個 ID 列表,因此您的 $in 成為列表列表 ([[]])。 試試這個:
{ $match: { "owner._id": { $in: id } } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.