From 3bdae61fc79a55ddbe966622c2313614e0503f2a Mon Sep 17 00:00:00 2001 From: hasezoey Date: Fri, 16 Jun 2023 12:41:07 +0200 Subject: [PATCH] types: augment bson.ObjectId instead of adding on own type fixes #12537 --- test/types/mongo.test.ts | 13 +++++++++++++ types/augmentations.d.ts | 9 +++++++++ types/index.d.ts | 1 + types/types.d.ts | 1 - 4 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 types/augmentations.d.ts diff --git a/test/types/mongo.test.ts b/test/types/mongo.test.ts index 320ae24501b..42fda3587d7 100644 --- a/test/types/mongo.test.ts +++ b/test/types/mongo.test.ts @@ -1,4 +1,17 @@ import * as mongoose from 'mongoose'; import { expectType } from 'tsd'; +import * as bson from 'bson'; import GridFSBucket = mongoose.mongo.GridFSBucket; + +function gh12537() { + const schema = new mongoose.Schema({ test: String }); + const model = mongoose.model('Test', schema); + + const doc = new model({}); + + const v = new bson.ObjectId('somehex'); + expectType(v._id.toHexString()); + + doc._id = new bson.ObjectId('somehex'); +} diff --git a/types/augmentations.d.ts b/types/augmentations.d.ts new file mode 100644 index 00000000000..6ed3e6f2c93 --- /dev/null +++ b/types/augmentations.d.ts @@ -0,0 +1,9 @@ +// the import below is said to be unused, but actually required so that types get merged and not overwritten +import * as bson from 'bson'; + +declare module 'bson' { + interface ObjectId { + /** Mongoose automatically adds a conveniency "_id" getter on the base ObjectId class */ + _id: this; + } +} diff --git a/types/index.d.ts b/types/index.d.ts index cfed86c51c3..ec716fa29d3 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -22,6 +22,7 @@ /// /// /// +/// declare class NativeDate extends global.Date { } diff --git a/types/types.d.ts b/types/types.d.ts index 29652243403..55b48138ad3 100644 --- a/types/types.d.ts +++ b/types/types.d.ts @@ -80,7 +80,6 @@ declare module 'mongoose' { } class ObjectId extends mongodb.ObjectId { - _id: this; } class Subdocument extends Document {