Skip to content

Commit

Permalink
types: augment bson.ObjectId instead of adding on own type
Browse files Browse the repository at this point in the history
  • Loading branch information
hasezoey committed Jun 16, 2023
1 parent 1db7cf4 commit 3bdae61
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 1 deletion.
13 changes: 13 additions & 0 deletions 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<string>(v._id.toHexString());

doc._id = new bson.ObjectId('somehex');
}
9 changes: 9 additions & 0 deletions 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;
}
}
1 change: 1 addition & 0 deletions types/index.d.ts
Expand Up @@ -22,6 +22,7 @@
/// <reference path="./validation.d.ts" />
/// <reference path="./inferschematype.d.ts" />
/// <reference path="./virtuals.d.ts" />
/// <reference path="./augmentations.d.ts" />

declare class NativeDate extends global.Date { }

Expand Down
1 change: 0 additions & 1 deletion types/types.d.ts
Expand Up @@ -80,7 +80,6 @@ declare module 'mongoose' {
}

class ObjectId extends mongodb.ObjectId {
_id: this;
}

class Subdocument<IdType = any> extends Document<IdType> {
Expand Down

0 comments on commit 3bdae61

Please sign in to comment.