i’m working with products and categories
i need that product model’s categories type to be an array of Category
i’ve created these two types
type Category = {
parent: Category | null; // is this ok?
name: String;
};
type Product = {
categories: Category[];
name: String;
qty: Number;
price: Number;
};
then i’ve created the models
// category model
import { Schema, Types, model } from "mongoose";
import Category from "../types/Category";
const categorySchema = new Schema(
{
parent: { type: Category | null, required: true }, // NEED HELP WITH THIS TYPE
name: { type: String, required: true },
},
{ timestamps: true }
);
export default model("Category", categorySchema);
// product model
import { Schema, Types, model } from "mongoose";
import Category from "../types/Category";
const productSchema = new Schema(
{
categories: { type: [Category], required: true }, // NEED HELP WITH THIS TYPE
name: { type: String, required: true }
qty: { type: Number, required: true }
price: { type: Number, required: true }
},
{ timestamps: true }
);
export default model("Product", productSchema);
vs code shows no error but when i run the server that’s the error i get:
isn’t productSchema’s categories type an array of Category?
i’ve also tried categories: { type: Types.Array<Category>, required: true }
with no success
if i pass the categorySchema like this
// product model
import { Schema, Types, model } from "mongoose";
import categorySchema from "./category.model";
const productSchema = new Schema( // should i pass something here? like Schema<xxxxxxx>
{
categories: { type: [categorySchema], required: true }, // categorySchema instead of Category type
name: { type: String, required: true }
qty: { type: Number, required: true }
price: { type: Number, required: true }
},
{ timestamps: true }
);
export default model("Product", productSchema);
it fails as well
thanks
2
Answers
You can give a reference to the category model in the product schema. Use this it will help you.
You can reference the
Category
model in both cases:You will need to
populate
the categories on retrieval: