Skip to content

Commit

Permalink
fix(findOneAndReplace): throw error if atomic operators provided for …
Browse files Browse the repository at this point in the history
…findOneAndReplace

Fixes NODE-1973
  • Loading branch information
kvwalker committed May 29, 2019
1 parent 9eb7fe7 commit 6a860a3
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,13 @@ Collection.prototype.findOneAndReplace = function(filter, replacement, options,
if (replacement == null || typeof replacement !== 'object')
throw toError('replacement parameter must be an object');

// Check that there are no atomic operators
const keys = Object.keys(replacement);

if (keys[0] && keys[0][0] === '$') {
throw toError('The replacement document must not contain atomic operators.');
}

return executeOperation(this.s.topology, findOneAndReplace, [
this,
filter,
Expand Down
20 changes: 20 additions & 0 deletions test/functional/collection_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1898,4 +1898,24 @@ describe('Collection', function() {
}
});
});

it('should allow an empty replacement document for findOneAndReplace', function() {
const configuration = this.configuration;
const client = configuration.newClient({}, { w: 1 });

client.connect((err, client) => {
expect(err).to.be.null;

const db = client.db(configuration.db);
const collection = db.collection('find_one_and_replace');

collection.insertOne({ a: 1 }, err => {
expect(err).to.be.null;

expect(collection.findOneAndReplace.bind(collection, { a: 1 }, {})).to.not.throw();
});

client.close();
});
});
});
32 changes: 32 additions & 0 deletions test/unit/collection_tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

const EventEmitter = require('events');
const chai = require('chai');
const expect = chai.expect;
const Db = require('../../lib/db');

class MockTopology extends EventEmitter {
constructor() {
super();
}

capabilities() {
return {};
}
}

describe('Collection', function() {
/**
* @ignore
*/
it('should not allow atomic operators for findOneAndReplace', {
metadata: { requires: { topology: 'single' } },
test: function() {
const db = new Db('fakeDb', new MockTopology());
const collection = db.collection('test');
expect(() => {
collection.findOneAndReplace({ a: 1 }, { $set: { a: 14 } });
}).to.throw('The replacement document must not contain atomic operators.');
}
});
});

0 comments on commit 6a860a3

Please sign in to comment.