Reputation: 1
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
Upvotes: 0
Views: 13