Модели ссылаются друг на друга ошибка: проблема с циклическими зависимостями

#node.js #typescript #mongodb #mongoose

Вопрос:

администратор.модель.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);
 

пользователь-роль.модель.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
 

Вот две мои модели, как я могу решить проблему такого типа и как справиться с циклическими зависимостями?

Комментарии:

1. Как вы получаете эту ошибку?

Ответ №1:

Вы должны поместить ref значения для UserRole и Admin в '' вот так:

 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
    }
})