使用populate时,我必须重命名字段的名称。
const CategorySchema = new Schema(
{
name: {
type: String,
unique: true
},
featured: {
type: Boolean,
default: true
},
image: String,
active: {
type: Boolean,
default: true
},
subCategoryIds: [{ type: Schema.Types.ObjectId, ref: 'SubCategory' }]
},
{
timestamps: true
}
);
export default mongoose.model('Category', CategorySchema);
这是我的类别架构。
这是我的SubCategory Schema
const SubCategory = new Schema(
{
name: {
type: String,
unique: true
},
active: {
type: Boolean,
default: true
},
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
productIds: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
},
{
timestamps: true
}
);
SubCategory.virtual('category', {
ref: 'Category',
localField: 'categoryId',
foreignField: '_id'
});
export default mongoose.model('SubCategory', SubCategory);
在这里我有一个categoryId
提交,当使用populate时,我希望它是'category',所以我使用virtual
来创建'category`。并实现了这一点
const subCategories = await SubCategory.find({}).populate('category');
但不幸的是它不起作用,它返回正常的subCategory
对象,并且没有类别存在。我错过了什么吗?
为什么不使用Mongodb
聚合管道,而不是使用mongoose virtuals
,你可以使用$lookup
并在填充时将catergoryId
更改为category。
试试这个:
const subCategories = await SubCategory.aggregate([{
$lookup : {
from : "categories",
localField : "categoryId",
foreginField : "_id",
as : "category"
},{
$unwind : "$category"
}])
localField
说要填充哪个字段,from
告诉monogdb从哪个集合填充,foreignField
告诉mongodb哪个字段与人口匹配,as
用于存储结果的字段,
$unwind
用于下一阶段,因为$lookup
返回一个数组,我们需要将它转换为类别对象
阅读Mongodb $lookup documentation了解更多信息。