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

问题描述 投票:2回答:1

使用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 mongoose-populate
1个回答
2
投票

为什么不使用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了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.