Skip to content

Commit 0af5143

Browse files
committed
fix(NODE-3760): fix isValid str/byte length match bug, add isValid test cases, remove throw-deprecation flag
1 parent 5221825 commit 0af5143

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

src/objectid.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,12 @@ export class ObjectId {
298298
}
299299

300300
if (typeof id === 'string') {
301-
return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
301+
if (id.length === 12) {
302+
const bytes = Buffer.from(id);
303+
return bytes.byteLength === 12;
304+
} else if (id.length === 24) {
305+
return checkForHexRegExp.test(id);
306+
}
302307
}
303308

304309
if (id instanceof ObjectId) {

test/mocha.opts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,3 @@
22
--require chai/register-expect
33
--require source-map-support/register
44
--timeout 10000
5-
--throw-deprecation

test/node/object_id_tests.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,20 @@ describe('ObjectId', function () {
269269
);
270270
});
271271

272+
it('should have isValid be true for 12-char length and 12-byte length string', function () {
273+
const plainASCIIstr = 'aaaaaaaaaaaa';
274+
expect(ObjectId.isValid(plainASCIIstr)).to.be.true;
275+
});
276+
277+
it('should have isValid be false for 12-char length but non-12-byte length string', function () {
278+
const characterCodesLargerThan256 = 'abcdefŽhijkl';
279+
const length12Not12Bytest1 = '🐶🐶🐶🐶🐶🐶';
280+
const length12Not12Bytest2 = 'value with é';
281+
expect(ObjectId.isValid(characterCodesLargerThan256)).to.be.false;
282+
expect(ObjectId.isValid(length12Not12Bytest1)).to.be.false;
283+
expect(ObjectId.isValid(length12Not12Bytest2)).to.be.false;
284+
});
285+
272286
it('should correctly interpret timestamps beyond 2038', function () {
273287
const farFuture = new Date('2040-01-01T00:00:00.000Z').getTime();
274288
expect(

0 commit comments

Comments
 (0)