I make an API in NextJS and use MongoDB Atlas for my cloud database. But I found an error 11000 duplicate key when I create a new role but with the same permissions.resource although I'm not set unique for the field in schema mongoose.
My code like this
// BaseSchema
import { Schema } from 'mongoose';
export class BaseSchema extends Schema {
constructor(schema: any) {
super(schema, { timestamps: true });
this.set('toJSON', {
virtuals: true,
versionKey: false,
transform: (doc, ret) => {
delete ret._id;
}
});
}
}
RoleModel.ts
const RoleModel = new BaseSchema(
{
name: {
type: String,
required: true,
unique: true
},
permissions: [
{
resource: {
type: Schema.Types.ObjectId,
ref: 'Resource',
required: true
},
actions: [
{
type: Schema.Types.ObjectId,
ref: 'ActionMethod',
required: true
}
]
}
]
}
);
export interface IRole {
id: string;
name: string;
permissions: [
{
resource: string | IResource;
actions: string[] | IActionMethod[];
}
];
}
interface IModel extends IRole, Document {}
export default mongoose.models.Role || mongoose.model<IModel>('Role', RoleModel);
ResourceModel.ts
const ResourceModel = new BaseSchema(
{
name: {
type: String,
required: true,
unique: true
}
}
);
// export like RoleModel.ts pattern
