Whenever a new document is created from a model in Mongo, an ObjectId
is automatically generated by the system and stored under the key "_id"
.
If the _id: ObjectId
is not explicitly defined in the model, it will still be generated. In such cases, when using methods like findById that require the ObjectId _id
of the document, accessing it might not be straightforward in Typescript.
Does this mean the only solution is to manually define this specific ObjectId
in the model?
To illustrate, here's a simple Document example (using Nest) without a manually defined _id:
@ObjectType("Package")
@InputType("PackageInput")
@Schema()
export class Package {
@Field(() => String)
@Prop({ type: String })
status: PackageStatusesEnums;
@Field(() => String)
@Prop()
statusReason: string;
@Prop({ type: Object })
dimensions: PackageDimensions;
@Field(() => String)
@Prop()
notes: string;
When trying to access the _id in code like this:
const pckgRes = await this.findById(pckg._id)
You may encounter a TS error:
Property '_id' does not exist on type 'Package'.ts(2339)