Mongodb Mongoose:正在尝试使用.virtual方法重命名

Mongodb Mongoose:正在尝试使用.virtual方法重命名,mongodb,mongoose,mongoose-populate,Mongodb,Mongoose,Mongoose Populate,使用“填充”时,我必须重命名字段的名称 const CategorySchema = new Schema( { name: { type: String, unique: true }, featured: { type: Boolean, default: true }, image: String, active: { type: Boolean, default:

使用“填充”时,我必须重命名字段的名称

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);
这是我的分类模式

这是我的子类别模式

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');
但不幸的是,它不工作,它返回正常的
子类别
对象,并且不存在类别。
我遗漏了什么吗?

为什么不使用
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
返回一个数组,我们需要将其转换为category对象

阅读更多信息