Skip to content

Commit

Permalink
Merge pull request #13034 from lpizzinidev/gh-13032
Browse files Browse the repository at this point in the history
schematype(UUID): added null check to prevent error on binaryToString conversion
  • Loading branch information
vkarpov15 committed Feb 15, 2023
2 parents 06585a8 + 5f315c4 commit 830af77
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/schema/uuid.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const Binary = MongooseBuffer.Binary;

function hex2buffer(hex) {
// use buffer built-in function to convert from hex-string to buffer
const buff = hex && Buffer.from(hex, 'hex');
const buff = hex != null && Buffer.from(hex, 'hex');
return buff;
}

Expand All @@ -36,7 +36,7 @@ function hex2buffer(hex) {

function binary2hex(buf) {
// use buffer built-in function to convert from buffer to hex-string
const hex = buf && buf.toString('hex');
const hex = buf != null && buf.toString('hex');
return hex;
}

Expand Down Expand Up @@ -66,8 +66,9 @@ function stringToBinary(uuidStr) {
*/
function binaryToString(uuidBin) {
// i(hasezoey) dont quite know why, but "uuidBin" may sometimes also be the already processed string
if (uuidBin && typeof uuidBin !== 'string') {
const hex = binary2hex(uuidBin);
let hex;
if (typeof uuidBin !== 'string' && uuidBin != null) {
hex = binary2hex(uuidBin);
const uuidStr = hex.substring(0, 8) + '-' + hex.substring(8, 8 + 4) + '-' + hex.substring(12, 12 + 4) + '-' + hex.substring(16, 16 + 4) + '-' + hex.substring(20, 20 + 12);
return uuidStr;
}
Expand Down
28 changes: 28 additions & 0 deletions test/schema.uuid.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const assert = require('assert');
const mongoose = start.mongoose;
const Schema = mongoose.Schema;

const { v4: uuidv4 } = require('uuid');

describe('SchemaUUID', function() {
let Model;
let TestSchema;
Expand Down Expand Up @@ -101,6 +103,32 @@ describe('SchemaUUID', function() {
assert.strictEqual(foundDocAll[0].y[2], '5b544b71-8988-422b-a4df-bf691939fe4e');
});

it('should not convert to string nullish UUIDs (gh-13032)', async function() {
const schema = new Schema({
_id: {
type: Schema.Types.UUID,
default: uuidv4(),
immutable: true
},
name: {
type: String,
required: true
},
organization: {
type: Schema.Types.UUID,
ref: 'Organization',
index: true
}
}, { _id: false });

const Test = db.model('gh_13032', schema);

const { name, organization } = await Test.create({ name: 'test' });

assert.equal(name, 'test');
assert.equal(organization, undefined);
});

// the following are TODOs based on SchemaUUID.prototype.$conditionalHandlers which are not tested yet
it('should work with $bits* operators');
it('should work with $all operator');
Expand Down

0 comments on commit 830af77

Please sign in to comment.