如何按深層嵌套填充欄位過濾產品。catalogProduct 是一個 ObjectId(參考目錄產品)。category 是 catalogProduct 中的 ObjectId(參考類別)。類別是類別 ID 的陣列。
products = await StorageModel
.find({"catalogProduct.category": {$in: categories }})
.skip((page-1)*8)
.limit(8)
.populate({path: "catalogProduct", populate: {path: "category", select: "name"}})
.select('-__v')
.sort({_id: -1});
uj5u.com熱心網友回復:
您需要對$lookupcatelogProduct 集合執行 a ,以便您可以訪問查詢中的 catelogProduct 資料。
不幸的是,這僅在使用 Mongo Aggregation 時可用,但是聚合非常強大,非常適合這種事情。你可以這樣做:
const products = await StorageModel.aggregate([
{ $lookup: { // Replace the Catelog Product ID with the Catelog Product
from: "catelogProduct",
localField: "catelogProduct",
foreignField: "_id",
as: "catelogProduct"
} },
{ $lookup: { // Replace the Category ID with the Category
from: "categories",
localField: "catelogProduct.category",
foreignField: "_id",
as: "catelogProduct.category"
} },
{ $addFields: { // Replace the Category with its name
"catelogProduct.category": "$catelogProduct.category.name"
} },
{ $match: {
"catalogProduct.category": { $in: categories }
} },
{ $sort: { _id: -1 } },
{ $skip: (page - 1) * 8 },
{ $limit: 8 }
]);
理想情況下,$lookup在對結果進行分頁(使用$skip和$limit)之前,您不會執行該操作,但在這種情況下,執行第$lookup一個操作是有意義的。確保你有一個索引catelogProduct._id并categories._id優化查詢。
有關 的更多資訊$lookup,請查看這篇文章。有關 Mongo 聚合的更多資訊,請查看這篇文章。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340252.html
標籤:javascript 数据库 MongoDB 猫鼬
上一篇:聚合以創建具有嵌套檔案值的檔案
下一篇:MongoDB計算唯一屬性
