Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle buffers stored in MongoDB as EJSON representation with { $binary } #14932

Merged
merged 1 commit into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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