diff --git a/lib/bson/bson.js b/lib/bson/bson.js index a864d952..9fadd5c6 100644 --- a/lib/bson/bson.js +++ b/lib/bson/bson.js @@ -96,7 +96,7 @@ BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, optio buffer, object, checkKeys, - startIndex || 0, + 0, 0, serializeFunctions, ignoreUndefined @@ -104,7 +104,7 @@ BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, optio buffer.copy(finalBuffer, startIndex, 0, serializationIndex); // Return the index - return serializationIndex - 1; + return startIndex + serializationIndex - 1; }; /** diff --git a/test/node/serialize_with_buffer_tests.js b/test/node/serialize_with_buffer_tests.js index 5b97a7e3..ab822c97 100644 --- a/test/node/serialize_with_buffer_tests.js +++ b/test/node/serialize_with_buffer_tests.js @@ -1,6 +1,6 @@ 'use strict'; -var createBSON = require('../utils'), +let createBSON = require('../utils'), expect = require('chai').expect; describe('serializeWithBuffer', function() { @@ -28,4 +28,40 @@ describe('serializeWithBuffer', function() { expect({ a: 1 }).to.deep.equal(doc); done(); }); + + it('correctly serialize 3 different docs into buffer using serializeWithBufferAndIndex', function( + done + ) { + const MAXSIZE = 1024 * 1024 * 17; + var bson = createBSON(); + let bf = new Buffer(MAXSIZE); + + const data = [ + { + a: 1, + b: new Date('2019-01-01') + }, + { + a: 2, + b: new Date('2019-01-02') + }, + { + a: 3, + b: new Date('2019-01-03') + } + ]; + + let idx = 0; + data.forEach(item => { + idx = + bson.serializeWithBufferAndIndex(item, bf, { + index: idx + }) + 1; + }); + + expect(bson.deserialize(bf.slice(0, 23))).to.deep.equal(data[0]); + expect(bson.deserialize(bf.slice(23, 46))).to.deep.equal(data[1]); + expect(bson.deserialize(bf.slice(46, 69))).to.deep.equal(data[2]); + done(); + }); });