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