typegoose: _id is undefined on virtual property

Versions

  • NodeJS: 12.13.0
  • Typegoose(NPM): 6.0.4
  • mongoose: 5.7.6
  • mongodb: 4.2.0 (docker 4.2.0-bionic)

What is the Problem?

I want my model to have a virtual property relayId but this._id always return undefined

Code Example

import { prop as Property } from '@typegoose/typegoose'
import { Base } from '@typegoose/typegoose/lib/defaultClasses'

@ObjectType({ implements: Node })
export class User extends Base implements Node {
  @Field(() => ID, { name: 'id' })
  public get relayId (): string {
    console.log(this._id) // undefined
    console.log(this._doc._id) // this works
    return toGlobalId('User', this._id) // undefined
  }
}

Do you know why it happenes?

no

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 22 (13 by maintainers)

Most upvoted comments

Current solution i found (for nestjs):

class Intercept implements NestInterceptor {
	public async intercept(
		context: import("@nestjs/common").ExecutionContext,
		next: import("@nestjs/common").CallHandler<any>
	): Promise<any> {
		Logger.log(format("hello from interceptor", ...arguments));

		return next.handle().pipe(map((data) => {
			if (data instanceof (mongoose as any).Document) {
				return data.toJSON({ virtuals: true });
			}

			return classToPlain(data);
		}));
	}
}

@Controller("cats")
@UseInterceptors(Intercept)
export class CatsController { }

instead of @UseInterceptors(ClassSerializerInterceptor) - they would conflict

OR

calling doc.toJSON / doc.toObject in each function that returns an document