mongodb does not show embedded object _id

739 views Asked by At

First note: I am using @nestjs/mongoose, i don't know if the problem because @nestjs/mongoose or pure mongodb.

I want to access embedded document's _id using @nestjs/mongoose. However mongoose document object does not contain embedded document's _id.

In my context, Category is embedded inside Topic. I want to reach Category's _id.

"Topic" definition:


import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { CategorySchema, Category } from './category.schema';

export type TopicDocument = Topic & Document;

@Schema()
export class Topic {
  @Prop()
  name: string;

  @Prop({ type: [CategorySchema] })
  categories: Category[];
}
export const TopicSchema = SchemaFactory.createForClass(Topic);

"Category" definition:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Activity, ActivitySchema } from './activity.schema';

export type CategoryDocument = Category & Document;

@Schema()
export class Category {
  @Prop({ _id: true })
  _id: number;
  @Prop()
  name: string;

  @Prop()
  image: string;

  @Prop({ type: [ActivitySchema] })
  activities: Activity[];
}

export const CategorySchema = SchemaFactory.createForClass(Category);

When I run this:

const topics: Topic[] = await this.topicModel.find({ _id: topicId }).exec();

This is the expected result:
enter image description here

However this is the result: (which does not contain embedded document's _id)

enter image description here

Is there any solution for this?

A side note: I am be able to get embedded document's _id using lean() instead of exec(), lean() returns JS object. However since its JS object it won't let me use save()

1

There are 1 answers

0
doruksahin On BEST ANSWER

Solved!

It looks like i must extend Document for id.
Adding id as a Prop is a wrong overriding option.

@Schema()
export class Category extends Document {
  @Prop()
  name: string;

  @Prop()
  image: string;

  @Prop({ type: [ActivitySchema] })
  activities: Activity[];
}