@@ -10,6 +10,12 @@ var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
10
10
11
11
// Regular expression that checks for hex value
12
12
var checkForHexRegExp = new RegExp ( "^[0-9a-fA-F]{24}$" ) ;
13
+ var hasBufferType = false ;
14
+
15
+ // Check if buffer exists
16
+ try {
17
+ if ( Buffer && Buffer . from ) hasBufferType = true ;
18
+ } catch ( err ) { } ;
13
19
14
20
/**
15
21
* Create a new ObjectID instance
@@ -26,17 +32,26 @@ var ObjectID = function ObjectID(id) {
26
32
27
33
this . _bsontype = 'ObjectID' ;
28
34
29
- var __id = null ;
35
+ // The most common usecase (blank id, new objectId instance)
36
+ if ( id == null || typeof id == 'number' ) {
37
+ // Generate a new id
38
+ this . id = this . generate ( id ) ;
39
+ // If we are caching the hex string
40
+ if ( ObjectID . cacheHexString ) this . __id = this . toString ( 'hex' ) ;
41
+ // Return the object
42
+ return ;
43
+ }
44
+
45
+ // Check if the passed in id is valid
30
46
var valid = ObjectID . isValid ( id ) ;
31
47
32
48
// Throw an error if it's not a valid setup
33
49
if ( ! valid && id != null ) {
34
50
throw new Error ( "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters" ) ;
51
+ } else if ( valid && typeof id == 'string' && id . length == 24 && hasBufferType ) {
52
+ return new ObjectID ( Buffer . from ( id , 'hex' ) ) ;
35
53
} else if ( valid && typeof id == 'string' && id . length == 24 ) {
36
54
return ObjectID . createFromHexString ( id ) ;
37
- } else if ( id == null || typeof id == 'number' ) {
38
- // convert to 12 byte binary string
39
- this . id = this . generate ( id ) ;
40
55
} else if ( id != null && id . length === 12 ) {
41
56
// assume 12 byte string
42
57
this . id = id ;
@@ -47,7 +62,7 @@ var ObjectID = function ObjectID(id) {
47
62
throw new Error ( "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters" ) ;
48
63
}
49
64
50
- if ( ObjectID . cacheHexString ) this . __id = this . toHexString ( ) ;
65
+ if ( ObjectID . cacheHexString ) this . __id = this . toString ( 'hex' ) ;
51
66
} ;
52
67
53
68
// Allow usage of ObjectId as well as ObjectID
@@ -155,7 +170,7 @@ ObjectID.prototype.generate = function(time) {
155
170
*/
156
171
ObjectID . prototype . toString = function ( format ) {
157
172
// Is the id a buffer then use the buffer toString method to return the format
158
- if ( this . id instanceof Buffer ) {
173
+ if ( this . id && this . id . copy ) {
159
174
return this . id . toString ( format || 'hex' ) ;
160
175
}
161
176
0 commit comments