Home > Enterprise >  importing schema from file causes ReferenceError: Cannot access 'MySchema' before initiali
importing schema from file causes ReferenceError: Cannot access 'MySchema' before initiali

Time:06-26

I have a schema that I export from a file

// Vendor.ts

export { ShortVendorSchema };

const ShortVendorSchema = new Schema<TShortVendor>({
    defaultVendor: Boolean,
    companyName: String,
    vendorId: { type: Schema.Types.ObjectId, ref: 'Vendor' },
});

and import it to another schema

// Order.ts
import { ShortVendorSchema } from './Vendor';

const OrderSchema = new Schema<TOrderSchema>(
    {
        status: {
            type: String,
            enum: Object.keys(ORDER_STATUS),
            default: 'NEW',
        },
        vendor: ShortVendorSchema,
    },
    { timestamps: true }
);

Whenever I'm trying to access Order model I get error error - ReferenceError: Cannot access 'ShortVendorSchema' before initialization

I have an idea why it happens, something about api routes living in isolation, but I don't know how to solve it without duplicating ShortVendorSchema in all files where it's used.

upd: moved all model exports into a single file, now I'm getting error error - TypeError: Cannot read properties of undefined (reading 'ShortVendorSchema')

Any ideas?

CodePudding user response:

The error occurs because of circular dependency.

I was importing ShortVendorSchema to Order.ts file and OrderSchema to Vendor.ts file.

The solution is to move ShortVendorSchema to a separate file that doesn't have any imports.

  • Related