@@ -7,6 +7,9 @@ import { NumberUtils } from './utils/number_utils';
77// Unique sequence for the current process (initialized on first use)
88let PROCESS_UNIQUE : Uint8Array | null = null ;
99
10+ /** ObjectId hexString cache @internal */
11+ const __idCache = new WeakMap ( ) ; // TODO(NODE-6549): convert this to #__id private field when target updated to ES2022
12+
1013/** @public */
1114export interface ObjectIdLike {
1215 id : string | Uint8Array ;
@@ -36,8 +39,6 @@ export class ObjectId extends BSONValue {
3639
3740 /** ObjectId Bytes @internal */
3841 private buffer ! : Uint8Array ;
39- /** ObjectId hexString cache @internal */
40- private __id ?: string ;
4142
4243 /**
4344 * Create ObjectId from a number.
@@ -111,6 +112,10 @@ export class ObjectId extends BSONValue {
111112 } else if ( typeof workingId === 'string' ) {
112113 if ( ObjectId . validateHexString ( workingId ) ) {
113114 this . buffer = ByteUtils . fromHex ( workingId ) ;
115+ // If we are caching the hex string
116+ if ( ObjectId . cacheHexString ) {
117+ __idCache . set ( this , workingId ) ;
118+ }
114119 } else {
115120 throw new BSONError (
116121 'input must be a 24 character hex string, 12 byte Uint8Array, or an integer'
@@ -119,10 +124,6 @@ export class ObjectId extends BSONValue {
119124 } else {
120125 throw new BSONError ( 'Argument passed in does not match the accepted types' ) ;
121126 }
122- // If we are caching the hex string
123- if ( ObjectId . cacheHexString ) {
124- this . __id = ByteUtils . toHex ( this . id ) ;
125- }
126127 }
127128
128129 /**
@@ -136,7 +137,7 @@ export class ObjectId extends BSONValue {
136137 set id ( value : Uint8Array ) {
137138 this . buffer = value ;
138139 if ( ObjectId . cacheHexString ) {
139- this . __id = ByteUtils . toHex ( value ) ;
140+ __idCache . set ( this , ByteUtils . toHex ( value ) ) ;
140141 }
141142 }
142143
@@ -165,14 +166,15 @@ export class ObjectId extends BSONValue {
165166
166167 /** Returns the ObjectId id as a 24 lowercase character hex string representation */
167168 toHexString ( ) : string {
168- if ( ObjectId . cacheHexString && this . __id ) {
169- return this . __id ;
169+ if ( ObjectId . cacheHexString ) {
170+ const __id = __idCache . get ( this ) ;
171+ if ( __id ) return __id ;
170172 }
171173
172174 const hexString = ByteUtils . toHex ( this . id ) ;
173175
174- if ( ObjectId . cacheHexString && ! this . __id ) {
175- this . __id = hexString ;
176+ if ( ObjectId . cacheHexString ) {
177+ __idCache . set ( this , hexString ) ;
176178 }
177179
178180 return hexString ;
@@ -370,6 +372,11 @@ export class ObjectId extends BSONValue {
370372 return new ObjectId ( doc . $oid ) ;
371373 }
372374
375+ /** @internal */
376+ private isCached ( ) : boolean {
377+ return ObjectId . cacheHexString && __idCache . has ( this ) ;
378+ }
379+
373380 /**
374381 * Converts to a string representation of this Id.
375382 *
0 commit comments