最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Populate in Mongoose doesn't work if I'm using Typescript Error: Schema hasn't been registered for model

programmeradmin1浏览0评论

I'm using NextJs 15 with TypeScript and Mongoose, but when I try to populate the Product fields with the category, I get the following error: Error: Schema hasn't been registered for model "Category". Use mongoose.model(name, schema).

 await connectDB();
  const newArrivals: HydratedDocument<ProductInterface & { category: CategoryInterface }>[] = await Product.find({ isLive: true })
    .sort({ _id: -1 })
    .limit(6)
    .populate("category")

These are my Product Schema and Model"

const ProductSchema = new Schema<ProductInterface>(
  {
    name: { type: String, required: true },
    description: { type: String, required: true },
    brand: { type: String, required: true },
    price: { type: Number, required: true },
    images: [{ type: String, required: true }],
    category: { type: Schema.Types.ObjectId, ref: "Category", required: true },
    gender: { type: String, required: true },
    stock: { type: Number, required: true },
    rating: { type: Number, required: true, max: 5 },
    discount: { type: Number },
    isFeatured: { type: Boolean, required: true },
    views: { type: Number, required: true },
    isLive: { type: Boolean, required: true },
  }
);

const Product =
  mongoose.models.Product ||
  mongoose.model<ProductInterface>("Product", ProductSchema);

export default Product;

export default interface ProductInterface {
  name: string;
  description: string;
  brand: string;
  price: number;
  images: string[];
  category: Types.ObjectId | CategoryInterface;
  gender: "men" | "women" | "unisex";
  stock: number;
  rating: number;
  discount?: number;
  isFeatured: boolean;
  views: number;
  isLive: boolean;
}

And these are my Category Schema and Model

export default interface CategoryInterface {
  name: string;
  description: string;
  image: string;
  isFeatured: boolean;
}

const CategorySchema = new Schema<CategoryInterface>({
  name: { type: String, required: true },
  description: { type: String, required: true },
  image:{type:String,required:true},
  isFeatured: { type: Boolean, required: true },
});

const Category =
  mongoose.models.Category ||
  mongoose.model<CategoryInterface>("Category", CategorySchema);

export default Category;

I've tried to change the capital letter from .populate('category') to .populate('Category') and in that case i get the error:

Error: Cannot populate path 'Category' because it is not in your schema. Set the 'strictPopulate' option to false to override.

I'va also tried to follow the mongoose docs on TypeScript Populate doing: .populate<{ category: HydratedDocument<CategoryInterface>}>('category') but nothing. Need some help plase as I'm completely Stucked

thanks

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论