Search code examples
typescriptmongodbexpressmongooseschema

Need help typing mongoose models


i'm working with products and categories

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: Types.Array<Category>, required: true },
        name: { type: String, required: true },
    },
    { timestamps: true }
);

export default model("Product", categorySchema);
// product model
import { Schema, Types, model } from "mongoose";
import Category from "../types/Category";

const productSchema = new Schema(
    {
        categories: { type: Types.Array<Category>, required: true },
        name: String,
        qty: Number,
        price: Number,
    },
    { timestamps: true }
);

export default model("Product", productSchema);

vs code shows no error but when i run the server that's the error i get:

TypeError: Invalid schema configuration: MongooseArray is not a valid type at path categories.

isn't productSchema's categories type an array of Category?

i've also tried categories: { type: [Category], required: true } with no success


Solution

  • there are may ways to do this but to be simple just use this

    const productSchema = new Schema(
        {
            categories: { type: [], required: true },
            name: String,
            qty: Number,
            price: Number,
        },
        { timestamps: true }
    );
    
    //this also works for me whenever I want to store an array or object
    //or just leaving category without a type
    
    const productSchema = new Schema(
        {
            categories: { [] , required: true },
            name: String,
            qty: Number,
            price: Number,
        },
        { timestamps: true }
    );