Mongoose model reference to self

hi. i’m working with two basic models: Category and Product

Category Model:

const categorySchema = new Schema(
    {
        parent:  xxxxxxxx                // how do i set "parent" to be Category or null?
        name: { type: String, required: true },
    },
    { timestamps: true }
);

Product Model:

const productSchema = new Schema(
    {
        categories:  xxxxxxxxx            // how do i set "categories" to be an array of Category? should i import Category interface (see below) or make a ref to Category model?
        name: { type: String, required: true }
        qty: { type: Number, required: true }
        price: { type: Number, required: true }
    },
    { timestamps: true }
);

Interfaces:

inferface Category  {
    parent: Category | null;  // is this ok?
    name: String;
};
interface Product {
    categories: Category[];
    name: String;
    qty: Number;
    price: Number;
};

thanks!

Hi :wave: @mongu,

Welcome to the MongoDB Community forums :sparkles:

Can you please confirm if my understanding of your use-case is correct? Are you intending to assign the parent field of the category schema to either “category” or “null” by default? If yes then you can use the referencing feature. Sharing the code snippet for reference:

const categorySchema = new mongoose.Schema(
    {
        parent: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', default: null },
        name: { type: String, required: true }
    },
    { timestamps: true }
);

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

You can perform the same action for the productSchema as well. Here is a code snippet for your reference:

const productSchema = new mongoose.Schema(
    {
        categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' }],
        name: { type: String, required: true },
        qty: { type: Number, required: true },
        price: { type: Number, required: true }
    },
    { timestamps: true }
);

const Product = mongoose.model('Product', productSchema);

I hope it helps. Let us know if you have any further queries.

Thanks,
Kushagra

it helps! then i do have to populate, right? do i have a link so i can read how populate works for cases like this? thank you very much, @Kushagra_Kesav !!

Hey @mongu,

Here is the link to the Mongoose documentation on populate: Mongoose v7.1.0: Query Population

Best,
Kushagra