Skip to content

Commit a585a0c

Browse files
authored
fix: make inspect method for ObjectId work (#412)
The previous Object.defineProperty() calls did not work because they did not specify a property descriptor. Adds `inspect` and inspect symbol methods directly to the ObjectId class. NODE-2875
1 parent 203402f commit a585a0c

File tree

2 files changed

+15
-20
lines changed

2 files changed

+15
-20
lines changed

src/objectid.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,20 @@ export class ObjectId {
338338
static fromExtendedJSON(doc: ObjectIdExtended): ObjectId {
339339
return new ObjectId(doc.$oid);
340340
}
341+
342+
/**
343+
* Converts to a string representation of this Id.
344+
*
345+
* @returns return the 24 character hex string representation.
346+
* @internal
347+
*/
348+
[Symbol.for('nodejs.util.inspect.custom')](): string {
349+
return this.inspect();
350+
}
351+
352+
inspect(): string {
353+
return `ObjectId("${this.toHexString()}")`;
354+
}
341355
}
342356

343357
// Deprecated methods
@@ -360,14 +374,4 @@ Object.defineProperty(ObjectId, 'get_inc', {
360374
value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead')
361375
});
362376

363-
const inspect = Symbol.for('nodejs.util.inspect.custom');
364-
/**
365-
* Converts to a string representation of this Id.
366-
*
367-
* @returns return the 24 character hex string representation.
368-
* @internal
369-
*/
370-
Object.defineProperty(ObjectId.prototype, inspect, ObjectId.prototype.toString);
371-
Object.defineProperty(ObjectId.prototype, 'inspect', ObjectId.prototype.toString);
372-
373377
Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });

test/node/object_id_tests.js

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,7 @@ describe('ObjectId', function () {
6666
it('should correctly allow for node.js inspect to work with ObjectId', function (done) {
6767
var a = 'AAAAAAAAAAAAAAAAAAAAAAAA';
6868
var b = new ObjectId(a);
69-
util.inspect(b);
70-
71-
// var c = b.equals(a); // => false
72-
// expect(true).to.equal(c);
73-
//
74-
// var a = 'aaaaaaaaaaaaaaaaaaaaaaaa';
75-
// var b = new ObjectId(a);
76-
// var c = b.equals(a); // => true
77-
// expect(true).to.equal(c);
78-
// expect(a).to.equal(b.toString());
69+
expect(util.inspect(b)).to.equal('ObjectId("aaaaaaaaaaaaaaaaaaaaaaaa")');
7970

8071
done();
8172
});

0 commit comments

Comments
 (0)