[英]Find documents in mongodb using mongoose
我有兩個分開的 collections 一個用於產品,一個用於類別 我的產品架構:
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: true },
catalogNumber: { type: Number, required: true },
barCode: { type: Number, required: true },
quantity: { type: String, required: true },
transportPackages: { type: String, required: true },
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "ProductCategory",
required: true,
},
translation: {
en: {
name: { type: String, required: true },
description: { type: String, required: true },
},
},
});
我的類別架構:
const productCategorySchema = new mongoose.Schema({
name: { type: String, required: true },
path: { type: String, require: true },
translate: {
en: {
name: { type: String, required: true },
},
},
});
您需要按產品中設置的類別查找,您必須確保在創建產品時為其分配了一個類別,然后您可以使用:
Product.find({category: req.body.category})
.populate([{ path: 'category'}])
.exec((error, populatedProduct) => {
return res.send(populatedProduct)
})
它將與產品一起返回類別信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.