Home > other >  ReferenceError: Cannot access 'User' before initialization mongoose
ReferenceError: Cannot access 'User' before initialization mongoose

Time:12-17

this error is shown by mongoose Cannot access 'User' before initialization at file:///C:/Users/Ayush Chugh/Desktop/pizzeria/models/order.model.js:6:52

but User is already there

order.js

import mongoose from 'mongoose';
import Product from './product.model.js';
import User from './users.model.js';

const orderSchema = new mongoose.Schema({
    user: { type: mongoose.SchemaTypes.ObjectId, ref: User },
    products: [{ type: mongoose.SchemaTypes.ObjectId, ref: Product }],
    status: { type: String, required: true },
});

const Order = mongoose.model('Order', orderSchema);

export default Order;

user.js

import mongoose from 'mongoose';
import Order from './order.model.js';

const userSchema = new mongoose.Schema({
    fname: { type: String, required: true },
    lname: { type: String, required: true },
    email: { type: String, required: true },
    phone: { type: Number, required: true },
    password: { type: String, required: true },
    orders: [{ type: mongoose.SchemaTypes.ObjectId, ref: Order }],
});

const User = mongoose.model('User', userSchema);

export default User;

CodePudding user response:

No need to import User model, try using following code

user: { type: mongoose.SchemaTypes.ObjectId, ref: 'User' },
  • Related