gpt4 book ai didi

node.js - 模型相互引用错误 : circular dependencies problem

转载 作者:行者123 更新时间:2023-12-04 14:55:18 24 4
gpt4 key购买 nike

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

用户角色.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

这是我的两个模型,如何解决此类问题以及如何处理循环依赖?

最佳答案

您必须将 UserRoleAdminref 值放在 '' 中,如下所示:

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

关于node.js - 模型相互引用错误 : circular dependencies problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68167071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com