#MongoDB Schema with NestJS
12 messages · Page 1 of 1 (latest)
User Schema:
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import mongoose from 'mongoose';
import { ServiceLocation } from './ServiceLocation.schema';
import { Exclude, Type } from 'class-transformer';
import { Hizmet, Roles } from 'src/utils/constants';
import { FCMToken } from './FCMToken.schema';
import { SchoolCalendar } from './SchoolCalendar.schema';
import { InOut } from './InOut.schema';
@Schema({ timestamps: true })
export class User {
_id: mongoose.Schema.Types.ObjectId;
@Prop({ required: true })
first_name: string;
@Prop({ required: true })
last_name: string;
@Prop({ unique: true, required: true })
email: string;
@Prop({ required: true })
@Exclude()
password: string;
@Prop({ required: true, enum: Roles })
// @Prop({ required: true, enum: Object.keys(Roles) })
role: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: ServiceLocation.name })
serviceLocation?: ServiceLocation;
@Prop({ required: true, enum: Hizmet })
hizmet?: string;
// @Prop([InOut])
@Type(() => InOut)
inOut?: InOut[];
@Prop({
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: User.name,
})
created_By: User;
@Prop({ required: false, default: false })
@Exclude()
isDeleted: boolean;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: User.name }] })
parents?: User[];
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: SchoolCalendar.name })
schoolCalendar?: SchoolCalendar;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: FCMToken.name })
fcmTokens?: FCMToken;
}
export const UserSchema = SchemaFactory.createForClass(User);
InOut Schema:
@Schema({ timestamps: true })
export class InOut {
@Prop({ required: false, default: new Date() })
leavedAt: Date;
@Prop({ required: true })
leaveReason: string;
@Prop({ required: false })
enteredAt: Date;
@Prop({ required: false, default: false })
isLate: boolean;
}
The Error:
Try changing your refs to something like this:
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: () => User }] })
parents?: User[];
I believe because the ref is relating to itself, the .name property isn't yet created when the class is first analyzed, so it fails. If that doesn't work, you'll need to use a string 'User'.
Or switch to Typegoose, where the above code I suggested works for sure.
Actually, in Typegoose, it is much simpler, cleaner and more logical, if you ask me.
@Prop({ ref: () => [User] })
parents?: User[];