Skip to content

Commit 4757bcd

Browse files
committed
fix: handle buffers stored in MongoDB as EJSON representation with { $binary }
Fix Automattic#14911
1 parent 136cab5 commit 4757bcd

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

lib/schema/buffer.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,14 @@ SchemaBuffer.prototype.cast = function(value, doc, init) {
219219
return ret;
220220
}
221221

222+
if (utils.isPOJO(value) && (value.$binary instanceof Binary || typeof value.$binary === 'string')) {
223+
const buf = this.cast(Buffer.from(value.$binary, 'base64'));
224+
if (value.$type != null) {
225+
buf._subtype = value.$type;
226+
return buf;
227+
}
228+
}
229+
222230
throw new CastError('Buffer', value, this.path, null, this);
223231
};
224232

test/document.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13926,6 +13926,35 @@ describe('document', function() {
1392613926
cur.subdocs[0] = { test: 'updated' };
1392713927
await savedDoc.save();
1392813928
});
13929+
13930+
it('handles buffers stored as EJSON POJO (gh-14911)', async function() {
13931+
const pdfSchema = new mongoose.Schema({
13932+
pdfSettings: {
13933+
type: {
13934+
_id: false,
13935+
fileContent: { type: Buffer, required: true },
13936+
filePreview: { type: Buffer, required: true },
13937+
fileName: { type: String, required: true }
13938+
}
13939+
}
13940+
});
13941+
const PdfModel = db.model('Test', pdfSchema);
13942+
13943+
const _id = new mongoose.Types.ObjectId();
13944+
const buf = { $binary: Buffer.from('hello', 'utf8').toString('base64'), $type: '00' };
13945+
await PdfModel.collection.insertOne({
13946+
_id,
13947+
pdfSettings: {
13948+
fileContent: buf,
13949+
filePreview: buf,
13950+
fileName: 'sample.pdf'
13951+
}
13952+
});
13953+
13954+
const reloaded = await PdfModel.findById(_id);
13955+
assert.ok(Buffer.isBuffer(reloaded.pdfSettings.fileContent));
13956+
assert.strictEqual(reloaded.pdfSettings.fileContent.toString('utf8'), 'hello');
13957+
});
1392913958
});
1393013959

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

0 commit comments

Comments
 (0)