@@ -7,6 +7,9 @@ import { NumberUtils } from './utils/number_utils';
7
7
// Unique sequence for the current process (initialized on first use)
8
8
let PROCESS_UNIQUE : Uint8Array | null = null ;
9
9
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
+
10
13
/** @public */
11
14
export interface ObjectIdLike {
12
15
id : string | Uint8Array ;
@@ -36,8 +39,6 @@ export class ObjectId extends BSONValue {
36
39
37
40
/** ObjectId Bytes @internal */
38
41
private buffer ! : Uint8Array ;
39
- /** ObjectId hexString cache @internal */
40
- private __id ?: string ;
41
42
42
43
/**
43
44
* Create ObjectId from a number.
@@ -111,6 +112,10 @@ export class ObjectId extends BSONValue {
111
112
} else if ( typeof workingId === 'string' ) {
112
113
if ( ObjectId . validateHexString ( workingId ) ) {
113
114
this . buffer = ByteUtils . fromHex ( workingId ) ;
115
+ // If we are caching the hex string
116
+ if ( ObjectId . cacheHexString ) {
117
+ __idCache . set ( this , workingId ) ;
118
+ }
114
119
} else {
115
120
throw new BSONError (
116
121
'input must be a 24 character hex string, 12 byte Uint8Array, or an integer'
@@ -119,10 +124,6 @@ export class ObjectId extends BSONValue {
119
124
} else {
120
125
throw new BSONError ( 'Argument passed in does not match the accepted types' ) ;
121
126
}
122
- // If we are caching the hex string
123
- if ( ObjectId . cacheHexString ) {
124
- this . __id = ByteUtils . toHex ( this . id ) ;
125
- }
126
127
}
127
128
128
129
/**
@@ -136,7 +137,7 @@ export class ObjectId extends BSONValue {
136
137
set id ( value : Uint8Array ) {
137
138
this . buffer = value ;
138
139
if ( ObjectId . cacheHexString ) {
139
- this . __id = ByteUtils . toHex ( value ) ;
140
+ __idCache . set ( this , ByteUtils . toHex ( value ) ) ;
140
141
}
141
142
}
142
143
@@ -165,14 +166,15 @@ export class ObjectId extends BSONValue {
165
166
166
167
/** Returns the ObjectId id as a 24 lowercase character hex string representation */
167
168
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 ;
170
172
}
171
173
172
174
const hexString = ByteUtils . toHex ( this . id ) ;
173
175
174
- if ( ObjectId . cacheHexString && ! this . __id ) {
175
- this . __id = hexString ;
176
+ if ( ObjectId . cacheHexString ) {
177
+ __idCache . set ( this , hexString ) ;
176
178
}
177
179
178
180
return hexString ;
@@ -370,6 +372,11 @@ export class ObjectId extends BSONValue {
370
372
return new ObjectId ( doc . $oid ) ;
371
373
}
372
374
375
+ /** @internal */
376
+ private isCached ( ) : boolean {
377
+ return ObjectId . cacheHexString && __idCache . has ( this ) ;
378
+ }
379
+
373
380
/**
374
381
* Converts to a string representation of this Id.
375
382
*
0 commit comments