Next.js Discord

Discord Forum

"Circular" subdocuments in Mongoose

Unanswered
Da_v_id posted this in #help-forum
Open in Discord
I would like to create a Category schema which has a subcategories array of other categories, how can I achieve something like this without using the reference Object_id?

interface ICategory extends Document {
  name: string,
  description?: string,
  nature: categoryNatures,
  icon: LucideIcon,
  level: number,
  subCategories: Types.ObjectId[],

}

const categorySchema = new Schema<ICategory>({
  name: {
    type: String,
    trim: true,
    required: [true, 'Category name is required'],
    unique: true,
    maxlength: [32, 'Category name cannot exceed 32 characters'],
    text: true
  },
  description: {
    type: String,
    trim: true,
    maxlength: [200, 'Category description cannot exceed 200 characters'],
    text: true
  },
    nature: {
      type: String,
      required: [true, 'Category nature is required'],
      enum: Object.values(categoryNatures) as string[],
    },
    subCategories:{
      type: [Schema.Types.ObjectId],
      ref: 'Category'
    }
    
  },{})

  const Category = mongoose.models.Category || mongoose.model('Category', categorySchema);

  export default Category;

1 Reply

as a certain Guillermo Rauch suggested in 2011, you can adopt this strat:
const categorySchema :Schema<ICategory> = new Schema<ICategory>({
  name: {
    type: String,
    trim: true,
    required: [true, 'Category name is required'],
    unique: true,
    maxlength: [32, 'Category name cannot exceed 32 characters'],
    text: true
  },
  description: {
    type: String,
    trim: true,
    maxlength: [200, 'Category description cannot exceed 200 characters'],
    text: true
  },
  nature: {
    type: String,
    required: [true, 'Category nature is required'],
    enum: Object.values(categoryNatures) as string[]
  },
  icon: {
    type: String,
    required: [true, 'Category icon is required']
  },
  depth: {
    type: Number,
    max: [2, 'Category level cannot exceed 2'],
    min: [0, 'Category level cannot be less than 0'],
    default: 0,
    required: [true, 'Category level is required']
  }
});

categorySchema.add({
  subCategories:
  {
    type: [categorySchema],
    default: []
  }
});