I want to attach and see all the posts of the user inside posts
property of UserSchema
. The user/Author id is getting stored with posts. But when I try the get posts ids
I'm getting the following error.
@Prop([{ type: mongoose.Schema.Types.ObjectId, ref: BlogPost.name }])
^
TypeError: Cannot read properties of undefined (reading 'name')
at Object.<anonymous> (D:\Noum\Data\CYBRNODE\MAN STACK\Cybrnode-Blog-Backend\Cybr-Blog-Nest-Backend\src\schema\user.schema.ts:45:64)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
Blog Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
import mongoose, { Document } from 'mongoose';
import { User } from 'src/schema/user.schema';
@Schema({ timestamps: true })
export class BlogPost {
@ApiProperty({ required: true })
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
author: User;
}
export const postSchema = SchemaFactory.createForClass(BlogPost);
export type postDocument = BlogPost & Document;
User Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
import mongoose, { Document } from 'mongoose';
import { BlogPost } from 'src/schema/blog.schema';
@Schema({ timestamps: true })
export class User {
@ApiProperty()
@Prop([{ type: mongoose.Schema.Types.ObjectId, ref: BlogPost.name }])
posts: BlogPost[];
}
export const userSchema = SchemaFactory.createForClass(User);
export type userDocument = User & Document;
Also I've imported UserModule
into BlogPostModule
and vice versa. And exported
the services
of both modules.
I've tried with these as well. But Error is same
import { Document, Schema as MongooseSchema } from 'mongoose';
export class User extends Document{
@ApiProperty()
@Prop([{ type: MongooseSchema.Types.ObjectId, ref: BlogPost.name }])
posts: BlogPost[];
}
export const userSchema = SchemaFactory.createForClass(User);
export type userDocument = User & Document;