Skip to content

Commit

Permalink
Merge pull request #14932 from Automattic/vkarpov15/gh-14911
Browse files Browse the repository at this point in the history
fix: handle buffers stored in MongoDB as EJSON representation with { $binary }
  • Loading branch information
vkarpov15 authored Oct 7, 2024
2 parents e7d7652 + 4757bcd commit 048eebc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/schema/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,14 @@ SchemaBuffer.prototype.cast = function(value, doc, init) {
return ret;
}

if (utils.isPOJO(value) && (value.$binary instanceof Binary || typeof value.$binary === 'string')) {
const buf = this.cast(Buffer.from(value.$binary, 'base64'));
if (value.$type != null) {
buf._subtype = value.$type;
return buf;
}
}

throw new CastError('Buffer', value, this.path, null, this);
};

Expand Down
29 changes: 29 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13926,6 +13926,35 @@ describe('document', function() {
cur.subdocs[0] = { test: 'updated' };
await savedDoc.save();
});

it('handles buffers stored as EJSON POJO (gh-14911)', async function() {
const pdfSchema = new mongoose.Schema({
pdfSettings: {
type: {
_id: false,
fileContent: { type: Buffer, required: true },
filePreview: { type: Buffer, required: true },
fileName: { type: String, required: true }
}
}
});
const PdfModel = db.model('Test', pdfSchema);

const _id = new mongoose.Types.ObjectId();
const buf = { $binary: Buffer.from('hello', 'utf8').toString('base64'), $type: '00' };
await PdfModel.collection.insertOne({
_id,
pdfSettings: {
fileContent: buf,
filePreview: buf,
fileName: 'sample.pdf'
}
});

const reloaded = await PdfModel.findById(_id);
assert.ok(Buffer.isBuffer(reloaded.pdfSettings.fileContent));
assert.strictEqual(reloaded.pdfSettings.fileContent.toString('utf8'), 'hello');
});
});

describe('Check if instance function that is supplied in schema option is available', function() {
Expand Down

0 comments on commit 048eebc

Please sign in to comment.