Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Models ref each other error: circular dependencies problem

admin.model.ts

import mongoose, { Schema, Document } from 'mongoose';
import UserRole, { IUserRole } from './user-role.model';

export interface IAdmin extends Document {
    role: IUserRole;
}

let adminSchema = new Schema<IAdmin>({
    role: {
        type: Schema.Types.ObjectId, ref: UserRole
    }
});

export default mongoose.model<IAdmin>('Admin', adminSchema);

user-role.model.ts

import { Schema, Document, model } from 'mongoose';

export interface IUserRole extends Document{
    updated_by: IAdmin|string;
}

let userRoleSchema = new Schema<IUserRole>({
    updated_by: {
        type: Schema.Types.ObjectId, ref: Admin
    }
})

export default model<IUserRole>('UserRole', userRoleSchema);
MongooseError: Invalid ref at path "updated_by". Got undefined
    at validateRef (/home/ess24/ess-smartlotto/node-rest/node_modules/mongoose/lib/helpers/populate/validateRef.js:17:9)
    at Schema.path (/home/ess24/ess-smartlotto/node-rest/node_modules/mongoose/lib/schema.js:655:5)
    at Schema.add (/home/ess24/ess-smartlotto/node-rest/node_modules/mongoose/lib/schema.js:535:14)
    at require (internal/modules/cjs/helpers.js:88:18)
[ERROR] 22:25:54 MongooseError: Invalid ref at path "updated_by". Got undefined

Here is my two model how can I solve this type of problem and how to deal with circular dependencies?

like image 604
MD. RAKIB HASAN Avatar asked Nov 04 '25 16:11

MD. RAKIB HASAN


1 Answers

You have to put the ref values for UserRole and Admin in '' like this:

const adminSchema = new Schema<IAdmin>({
    role: {
        type: Schema.Types.ObjectId, ref: 'UserRole' // Name of the model you are referencing
    }
});
let userRoleSchema = new Schema<IUserRole>({
    updated_by: {
        type: Schema.Types.ObjectId, ref: 'Admin' // <- and here
    }
})
like image 144
Gabriel Lupu Avatar answered Nov 07 '25 09:11

Gabriel Lupu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!