How to get _id of Models in Mongoose (Typescript)

Viewed 2264

I'm using Mongoose to model mongodb object (node.js / nestJS)

Goal

I want to have the _id - which is automatically created by MongoDB - of an object in a POJO exposed. Because I need them on client side for some operations. (identify same objects, ...)

What I tried

export type GroupDocument = Group & Document;

@Schema()
export class Group {
    @Prop({ required: true })
    name: string;
}

Given the code above, I can access the _id when I use

const group: GroupDocument = this.findOne();

which is fine. In most of the cases I don't want to work with the whole GroupDocument object, because it has a lot of overhead and it's recommended to work with LeanDocuments as much as possible. But when I call .lean() on a GroupDocument, the _id gets lost and I can't access it anymore.

const group: = this.findOne().lean();

It works if I would extend my Group from Documents like so:

Group extends Document

But this isn't recommended by mongoose

I also thought about just putting the _id into the POJO like so:

@Schema()
export class Group {

    _id: string;

    @Prop({ required: true })
    name: string;
}

But this seems to me not an ideal solution.

All I want to do is to make it possible to call group.id / group._id on a lean object. Is there any way to achieve that without harming any best practices?

1 Answers

You have to define _id as:

import { Schema } from 'mongoose';
_id: Schema.Types.ObjectId

To return just the '_id' field you could use project in database and just return the _id field

Related