Refactoring day1

This commit is contained in:
2020-08-20 20:27:14 +02:00
parent 6aceefeb2f
commit b907489a75
481 changed files with 5321 additions and 5616 deletions

View File

@@ -8,11 +8,13 @@ const decorateWithReadConcern = require('../utils').decorateWithReadConcern;
const ensureIndexDb = require('./db_ops').ensureIndex;
const evaluate = require('./db_ops').evaluate;
const executeCommand = require('./db_ops').executeCommand;
const resolveReadPreference = require('../utils').resolveReadPreference;
const handleCallback = require('../utils').handleCallback;
const indexInformationDb = require('./db_ops').indexInformation;
const Long = require('../core').BSON.Long;
const MongoError = require('../core').MongoError;
const ReadPreference = require('../core').ReadPreference;
const toError = require('../utils').toError;
const insertDocuments = require('./common_functions').insertDocuments;
const updateDocuments = require('./common_functions').updateDocuments;
@@ -50,6 +52,24 @@ const updateDocuments = require('./common_functions').updateDocuments;
const groupFunction =
'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}';
// Check the update operation to ensure it has atomic operators.
function checkForAtomicOperators(update) {
if (Array.isArray(update)) {
return update.reduce((err, u) => err || checkForAtomicOperators(u), null);
}
const keys = Object.keys(update);
// same errors as the server would give for update doc lacking atomic operators
if (keys.length === 0) {
return toError('The update operation document must contain at least one atomic operator.');
}
if (keys[0][0] !== '$') {
return toError('the update operation document must contain atomic operators.');
}
}
/**
* Create an index on the db and collection.
*
@@ -168,7 +188,7 @@ function group(coll, keys, condition, initial, reduce, finalize, command, option
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = ReadPreference.resolve(coll, options);
options.readPreference = resolveReadPreference(coll, options);
// Do we have a readConcern specified
decorateWithReadConcern(selector, coll, options);
@@ -341,6 +361,7 @@ function save(coll, doc, options, callback) {
}
module.exports = {
checkForAtomicOperators,
createIndex,
createIndexes,
ensureIndex,

View File

@@ -7,6 +7,7 @@ const debugOptions = require('../utils').debugOptions;
const handleCallback = require('../utils').handleCallback;
const MongoError = require('../core').MongoError;
const ReadPreference = require('../core').ReadPreference;
const resolveReadPreference = require('../utils').resolveReadPreference;
const MongoDBNamespace = require('../utils').MongoDBNamespace;
const debugFields = [
@@ -37,9 +38,9 @@ class CommandOperation extends OperationBase {
if (!this.hasAspect(Aspect.WRITE_OPERATION)) {
if (collection != null) {
this.options.readPreference = ReadPreference.resolve(collection, options);
this.options.readPreference = resolveReadPreference(collection, options);
} else {
this.options.readPreference = ReadPreference.resolve(db, options);
this.options.readPreference = resolveReadPreference(db, options);
}
} else {
if (collection != null) {

View File

@@ -2,12 +2,12 @@
const Aspect = require('./operation').Aspect;
const OperationBase = require('./operation').OperationBase;
const ReadPreference = require('../core').ReadPreference;
const resolveReadPreference = require('../utils').resolveReadPreference;
const ReadConcern = require('../read_concern');
const WriteConcern = require('../write_concern');
const maxWireVersion = require('../core/utils').maxWireVersion;
const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern;
const MongoError = require('../core/error').MongoError;
const MongoError = require('../error').MongoError;
const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5;
@@ -16,10 +16,9 @@ class CommandOperationV2 extends OperationBase {
super(options);
this.ns = parent.s.namespace.withCollection('$cmd');
const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent;
this.readPreference = ReadPreference.resolve(propertyProvider, this.options);
this.readConcern = resolveReadConcern(propertyProvider, this.options);
this.writeConcern = resolveWriteConcern(propertyProvider, this.options);
this.readPreference = resolveReadPreference(parent, this.options);
this.readConcern = resolveReadConcern(parent, this.options);
this.writeConcern = resolveWriteConcern(parent, this.options);
this.explain = false;
if (operationOptions && typeof operationOptions.fullResponse === 'boolean') {
@@ -98,11 +97,11 @@ class CommandOperationV2 extends OperationBase {
}
function resolveWriteConcern(parent, options) {
return WriteConcern.fromOptions(options) || (parent && parent.writeConcern);
return WriteConcern.fromOptions(options) || parent.writeConcern;
}
function resolveReadConcern(parent, options) {
return ReadConcern.fromOptions(options) || (parent && parent.readConcern);
return ReadConcern.fromOptions(options) || parent.readConcern;
}
module.exports = CommandOperationV2;

View File

@@ -297,9 +297,6 @@ function removeDocuments(coll, selector, options, callback) {
} else if (finalOptions.retryWrites) {
finalOptions.retryWrites = false;
}
if (options.hint) {
op.hint = options.hint;
}
// Have we specified collation
try {

View File

@@ -33,11 +33,9 @@ const legacyParse = deprecate(
const AUTH_MECHANISM_INTERNAL_MAP = {
DEFAULT: 'default',
PLAIN: 'plain',
GSSAPI: 'gssapi',
'MONGODB-CR': 'mongocr',
PLAIN: 'plain',
'MONGODB-X509': 'x509',
'MONGODB-AWS': 'mongodb-aws',
'SCRAM-SHA-1': 'scram-sha-1',
'SCRAM-SHA-256': 'scram-sha-256'
};
@@ -68,13 +66,12 @@ const monitoringEvents = [
const VALID_AUTH_MECHANISMS = new Set([
'DEFAULT',
'PLAIN',
'GSSAPI',
'MONGODB-CR',
'PLAIN',
'MONGODB-X509',
'MONGODB-AWS',
'SCRAM-SHA-1',
'SCRAM-SHA-256'
'SCRAM-SHA-256',
'GSSAPI'
]);
const validOptionNames = [
@@ -154,8 +151,6 @@ const validOptionNames = [
'tlsCertificateKeyFilePassword',
'minHeartbeatFrequencyMS',
'heartbeatFrequencyMS',
'directConnection',
'appName',
// CMAP options
'maxPoolSize',
@@ -649,7 +644,6 @@ function generateCredentials(client, username, password, options) {
// authMechanism
const authMechanismRaw = options.authMechanism || 'DEFAULT';
const authMechanism = authMechanismRaw.toUpperCase();
const mechanismProperties = options.authMechanismProperties;
if (!VALID_AUTH_MECHANISMS.has(authMechanism)) {
throw MongoError.create({
@@ -658,9 +652,18 @@ function generateCredentials(client, username, password, options) {
});
}
if (authMechanism === 'GSSAPI') {
return new MongoCredentials({
mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi',
mechanismProperties: options,
source,
username,
password
});
}
return new MongoCredentials({
mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism],
mechanismProperties,
source,
username,
password

View File

@@ -4,11 +4,13 @@ const Aspect = require('./operation').Aspect;
const defineAspects = require('./operation').defineAspects;
const CommandOperation = require('./command');
const applyWriteConcern = require('../utils').applyWriteConcern;
const handleCallback = require('../utils').handleCallback;
const loadCollection = require('../dynamic_loaders').loadCollection;
const MongoError = require('../core').MongoError;
const ReadPreference = require('../core').ReadPreference;
const ILLEGAL_COMMAND_FIELDS = new Set([
// Filter out any write concern options
const illegalCommandFields = [
'w',
'wtimeout',
'j',
@@ -22,11 +24,12 @@ const ILLEGAL_COMMAND_FIELDS = new Set([
'session',
'readConcern',
'writeConcern'
]);
];
class CreateCollectionOperation extends CommandOperation {
constructor(db, name, options) {
super(db, options);
this.name = name;
}
@@ -34,12 +37,14 @@ class CreateCollectionOperation extends CommandOperation {
const name = this.name;
const options = this.options;
// Create collection command
const cmd = { create: name };
// Add all optional parameters
for (let n in options) {
if (
options[n] != null &&
typeof options[n] !== 'function' &&
!ILLEGAL_COMMAND_FIELDS.has(n)
illegalCommandFields.indexOf(n) === -1
) {
cmd[n] = options[n];
}
@@ -52,51 +57,61 @@ class CreateCollectionOperation extends CommandOperation {
const db = this.db;
const name = this.name;
const options = this.options;
const Collection = loadCollection();
let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options);
let Collection = loadCollection();
// Did the user destroy the topology
if (db.serverConfig && db.serverConfig.isDestroyed()) {
return callback(new MongoError('topology was destroyed'));
}
let listCollectionOptions = Object.assign({}, options, { nameOnly: true });
listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions);
function done(err) {
if (err) {
return callback(err);
}
try {
callback(
null,
new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)
);
} catch (err) {
callback(err);
}
}
const strictMode = listCollectionOptions.strict;
if (strictMode) {
db.listCollections({ name }, listCollectionOptions)
.setReadPreference(ReadPreference.PRIMARY)
.toArray((err, collections) => {
if (err) {
return callback(err);
}
if (collections.length > 0) {
return callback(
new MongoError(`Collection ${name} already exists. Currently in strict mode.`)
// Check if we have the name
db.listCollections({ name }, listCollectionOptions)
.setReadPreference(ReadPreference.PRIMARY)
.toArray((err, collections) => {
if (err != null) return handleCallback(callback, err, null);
if (collections.length > 0 && listCollectionOptions.strict) {
return handleCallback(
callback,
MongoError.create({
message: `Collection ${name} already exists. Currently in strict mode.`,
driver: true
}),
null
);
} else if (collections.length > 0) {
try {
return handleCallback(
callback,
null,
new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)
);
} catch (err) {
return handleCallback(callback, err);
}
}
super.execute(done);
// Execute command
super.execute(err => {
if (err) return handleCallback(callback, err);
try {
return handleCallback(
callback,
null,
new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)
);
} catch (err) {
return handleCallback(callback, err);
}
});
return;
}
// otherwise just execute the command
super.execute(done);
});
}
}
defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION);
module.exports = CreateCollectionOperation;

View File

@@ -2,116 +2,60 @@
const Aspect = require('./operation').Aspect;
const defineAspects = require('./operation').defineAspects;
const CommandOperationV2 = require('./command_v2');
const OperationBase = require('./operation').OperationBase;
const executeCommand = require('./db_ops').executeCommand;
const MongoError = require('../core').MongoError;
const parseIndexOptions = require('../utils').parseIndexOptions;
const maxWireVersion = require('../core/utils').maxWireVersion;
const ReadPreference = require('../core').ReadPreference;
const validIndexOptions = new Set([
'unique',
'partialFilterExpression',
'sparse',
'background',
'expireAfterSeconds',
'storageEngine',
'collation',
'bucketSize'
]);
class CreateIndexesOperation extends OperationBase {
constructor(collection, indexSpecs, options) {
super(options);
class CreateIndexesOperation extends CommandOperationV2 {
/**
* @ignore
*/
constructor(parent, collection, indexes, options) {
super(parent, options);
this.collection = collection;
// createIndex can be called with a variety of styles:
// coll.createIndex('a');
// coll.createIndex({ a: 1 });
// coll.createIndex([['a', 1]]);
// createIndexes is always called with an array of index spec objects
if (!Array.isArray(indexes) || Array.isArray(indexes[0])) {
this.onlyReturnNameOfCreatedIndex = true;
// TODO: remove in v4 (breaking change); make createIndex return full response as createIndexes does
const indexParameters = parseIndexOptions(indexes);
// Generate the index name
const name = typeof options.name === 'string' ? options.name : indexParameters.name;
// Set up the index
const indexSpec = { name, key: indexParameters.fieldHash };
// merge valid index options into the index spec
for (let optionName in options) {
if (validIndexOptions.has(optionName)) {
indexSpec[optionName] = options[optionName];
}
}
this.indexes = [indexSpec];
return;
}
this.indexes = indexes;
this.indexSpecs = indexSpecs;
}
/**
* @ignore
*/
execute(server, callback) {
const options = this.options;
const indexes = this.indexes;
execute(callback) {
const coll = this.collection;
const indexSpecs = this.indexSpecs;
let options = this.options;
const serverWireVersion = maxWireVersion(server);
const capabilities = coll.s.topology.capabilities();
// Ensure we generate the correct name if the parameter is not set
for (let i = 0; i < indexes.length; i++) {
// Did the user pass in a collation, check if our write server supports it
if (indexes[i].collation && serverWireVersion < 5) {
callback(
new MongoError(
`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`
)
);
return;
}
if (indexes[i].name == null) {
for (let i = 0; i < indexSpecs.length; i++) {
if (indexSpecs[i].name == null) {
const keys = [];
for (let name in indexes[i].key) {
keys.push(`${name}_${indexes[i].key[name]}`);
// Did the user pass in a collation, check if our write server supports it
if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {
return callback(new MongoError('server/primary/mongos does not support collation'));
}
for (let name in indexSpecs[i].key) {
keys.push(`${name}_${indexSpecs[i].key[name]}`);
}
// Set the name
indexes[i].name = keys.join('_');
indexSpecs[i].name = keys.join('_');
}
}
const cmd = { createIndexes: this.collection, indexes };
options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
if (options.commitQuorum != null) {
if (serverWireVersion < 9) {
callback(
new MongoError('`commitQuorum` option for `createIndexes` not supported on servers < 4.4')
);
return;
}
cmd.commitQuorum = options.commitQuorum;
}
// collation is set on each index, it should not be defined at the root
this.options.collation = undefined;
super.executeCommand(server, cmd, (err, result) => {
if (err) {
callback(err);
return;
}
callback(null, this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result);
});
// Execute the index
executeCommand(
coll.s.db,
{
createIndexes: coll.collectionName,
indexes: indexSpecs
},
options,
callback
);
}
}
defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.EXECUTE_WITH_SELECTION]);
defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION);
module.exports = CreateIndexesOperation;

View File

@@ -2,6 +2,7 @@
const applyWriteConcern = require('../utils').applyWriteConcern;
const Code = require('../core').BSON.Code;
const resolveReadPreference = require('../utils').resolveReadPreference;
const debugOptions = require('../utils').debugOptions;
const handleCallback = require('../utils').handleCallback;
const MongoError = require('../core').MongoError;
@@ -224,7 +225,7 @@ function executeCommand(db, command, options, callback) {
const dbName = options.dbName || options.authdb || db.databaseName;
// Convert the readPreference if its not a write
options.readPreference = ReadPreference.resolve(db, options);
options.readPreference = resolveReadPreference(db, options);
// Debug information
if (db.s.logger.isDebug())

View File

@@ -3,9 +3,7 @@
const OperationBase = require('./operation').OperationBase;
const Aspect = require('./operation').Aspect;
const defineAspects = require('./operation').defineAspects;
const ReadPreference = require('../core').ReadPreference;
const maxWireVersion = require('../core/utils').maxWireVersion;
const MongoError = require('../core/error').MongoError;
const resolveReadPreference = require('../utils').resolveReadPreference;
class FindOperation extends OperationBase {
constructor(collection, ns, command, options) {
@@ -13,20 +11,16 @@ class FindOperation extends OperationBase {
this.ns = ns;
this.cmd = command;
this.readPreference = ReadPreference.resolve(collection, this.options);
this.readPreference = resolveReadPreference(collection, this.options);
}
execute(server, callback) {
// copied from `CommandOperationV2`, to be subclassed in the future
this.server = server;
if (typeof this.cmd.allowDiskUse !== 'undefined' && maxWireVersion(server) < 4) {
callback(new MongoError('The `allowDiskUse` option is not supported on MongoDB < 3.2'));
return;
}
const cursorState = this.cursorState || {};
// TOOD: use `MongoDBNamespace` through and through
const cursorState = this.cursorState || {};
server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback);
}
}

View File

@@ -8,8 +8,6 @@ const executeCommand = require('./db_ops').executeCommand;
const formattedOrderClause = require('../utils').formattedOrderClause;
const handleCallback = require('../utils').handleCallback;
const ReadPreference = require('../core').ReadPreference;
const maxWireVersion = require('../core/utils').maxWireVersion;
const MongoError = require('../error').MongoError;
class FindAndModifyOperation extends OperationBase {
constructor(collection, query, sort, doc, options) {
@@ -88,21 +86,6 @@ class FindAndModifyOperation extends OperationBase {
return callback(err, null);
}
if (options.hint) {
// TODO: once this method becomes a CommandOperationV2 we will have the server
// in place to check.
const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0;
if (unacknowledgedWrite || maxWireVersion(coll.s.topology) < 8) {
callback(
new MongoError('The current topology does not support a hint on findAndModify commands')
);
return;
}
queryObject.hint = options.hint;
}
// Execute the command
executeCommand(coll.s.db, queryObject, options, (err, result) => {
if (err) return handleCallback(callback, err, null);

View File

@@ -9,11 +9,6 @@ class FindOneAndDeleteOperation extends FindAndModifyOperation {
finalOptions.fields = options.projection;
finalOptions.remove = true;
// Basic validation
if (filter == null || typeof filter !== 'object') {
throw new TypeError('Filter parameter must be an object');
}
super(collection, filter, finalOptions.sort, null, finalOptions);
}
}

View File

@@ -1,7 +1,6 @@
'use strict';
const FindAndModifyOperation = require('./find_and_modify');
const hasAtomicOperators = require('../utils').hasAtomicOperators;
class FindOneAndReplaceOperation extends FindAndModifyOperation {
constructor(collection, filter, replacement, options) {
@@ -12,18 +11,6 @@ class FindOneAndReplaceOperation extends FindAndModifyOperation {
finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false;
finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false;
if (filter == null || typeof filter !== 'object') {
throw new TypeError('Filter parameter must be an object');
}
if (replacement == null || typeof replacement !== 'object') {
throw new TypeError('Replacement parameter must be an object');
}
if (hasAtomicOperators(replacement)) {
throw new TypeError('Replacement document must not contain atomic operators');
}
super(collection, filter, finalOptions.sort, replacement, finalOptions);
}
}

View File

@@ -1,7 +1,6 @@
'use strict';
const FindAndModifyOperation = require('./find_and_modify');
const hasAtomicOperators = require('../utils').hasAtomicOperators;
class FindOneAndUpdateOperation extends FindAndModifyOperation {
constructor(collection, filter, update, options) {
@@ -13,18 +12,6 @@ class FindOneAndUpdateOperation extends FindAndModifyOperation {
typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false;
finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false;
if (filter == null || typeof filter !== 'object') {
throw new TypeError('Filter parameter must be an object');
}
if (update == null || typeof update !== 'object') {
throw new TypeError('Update parameter must be an object');
}
if (!hasAtomicOperators(update)) {
throw new TypeError('Update document requires atomic operators');
}
super(collection, filter, finalOptions.sort, update, finalOptions);
}
}

View File

@@ -7,7 +7,7 @@ const decorateCommand = require('../utils').decorateCommand;
const decorateWithReadConcern = require('../utils').decorateWithReadConcern;
const executeCommand = require('./db_ops').executeCommand;
const handleCallback = require('../utils').handleCallback;
const ReadPreference = require('../core').ReadPreference;
const resolveReadPreference = require('../utils').resolveReadPreference;
const toError = require('../utils').toError;
/**
@@ -58,7 +58,7 @@ class GeoHaystackSearchOperation extends OperationBase {
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = ReadPreference.resolve(coll, options);
options.readPreference = resolveReadPreference(coll, options);
// Do we have a readConcern specified
decorateWithReadConcern(commandObject, coll, options);

View File

@@ -9,7 +9,7 @@ const handleCallback = require('../utils').handleCallback;
const isObject = require('../utils').isObject;
const loadDb = require('../dynamic_loaders').loadDb;
const OperationBase = require('./operation').OperationBase;
const ReadPreference = require('../core').ReadPreference;
const resolveReadPreference = require('../utils').resolveReadPreference;
const toError = require('../utils').toError;
const exclusionList = [
@@ -60,7 +60,7 @@ class MapReduceOperation extends OperationBase {
let options = this.options;
const mapCommandHash = {
mapReduce: coll.collectionName,
mapreduce: coll.collectionName,
map: map,
reduce: reduce
};
@@ -80,7 +80,7 @@ class MapReduceOperation extends OperationBase {
options = Object.assign({}, options);
// Ensure we have the right read preference inheritance
options.readPreference = ReadPreference.resolve(coll, options);
options.readPreference = resolveReadPreference(coll, options);
// If we have a read preference and inline is not set as output fail hard
if (

View File

@@ -4,8 +4,7 @@ const Aspect = {
READ_OPERATION: Symbol('READ_OPERATION'),
WRITE_OPERATION: Symbol('WRITE_OPERATION'),
RETRYABLE: Symbol('RETRYABLE'),
EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION'),
NO_INHERIT_OPTIONS: Symbol('NO_INHERIT_OPTIONS')
EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION')
};
/**

View File

@@ -1,33 +1,28 @@
'use strict';
const Aspect = require('./operation').Aspect;
const defineAspects = require('./operation').defineAspects;
const CommandOperationV2 = require('./command_v2');
const serverType = require('../core/sdam/common').serverType;
const ServerType = require('../core/sdam/common').ServerType;
const MongoError = require('../core').MongoError;
const CommandOperation = require('./command');
const handleCallback = require('../utils').handleCallback;
class ReIndexOperation extends CommandOperationV2 {
class ReIndexOperation extends CommandOperation {
constructor(collection, options) {
super(collection, options);
this.collectionName = collection.collectionName;
super(collection.s.db, options, collection);
}
execute(server, callback) {
if (serverType(server) !== ServerType.Standalone) {
callback(new MongoError(`reIndex can only be executed on standalone servers.`));
return;
}
super.executeCommand(server, { reIndex: this.collectionName }, (err, result) => {
if (err) {
callback(err);
return;
}
callback(null, !!result.ok);
_buildCommand() {
const collection = this.collection;
const cmd = { reIndex: collection.collectionName };
return cmd;
}
execute(callback) {
super.execute((err, result) => {
if (callback == null) return;
if (err) return handleCallback(callback, err, null);
handleCallback(callback, null, result.ok ? true : false);
});
}
}
defineAspects(ReIndexOperation, [Aspect.EXECUTE_WITH_SELECTION]);
module.exports = ReIndexOperation;

View File

@@ -2,34 +2,27 @@
const OperationBase = require('./operation').OperationBase;
const updateDocuments = require('./common_functions').updateDocuments;
const hasAtomicOperators = require('../utils').hasAtomicOperators;
class ReplaceOneOperation extends OperationBase {
constructor(collection, filter, replacement, options) {
constructor(collection, filter, doc, options) {
super(options);
if (hasAtomicOperators(replacement)) {
throw new TypeError('Replacement document must not contain atomic operators');
}
this.collection = collection;
this.filter = filter;
this.replacement = replacement;
this.doc = doc;
}
execute(callback) {
const coll = this.collection;
const filter = this.filter;
const replacement = this.replacement;
const doc = this.doc;
const options = this.options;
// Set single document update
options.multi = false;
// Execute update
updateDocuments(coll, filter, replacement, options, (err, r) =>
replaceCallback(err, r, replacement, callback)
);
updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback));
}
}

View File

@@ -3,16 +3,11 @@
const OperationBase = require('./operation').OperationBase;
const updateCallback = require('./common_functions').updateCallback;
const updateDocuments = require('./common_functions').updateDocuments;
const hasAtomicOperators = require('../utils').hasAtomicOperators;
class UpdateManyOperation extends OperationBase {
constructor(collection, filter, update, options) {
super(options);
if (!hasAtomicOperators(update)) {
throw new TypeError('Update document requires atomic operators');
}
this.collection = collection;
this.filter = filter;
this.update = update;

View File

@@ -2,16 +2,11 @@
const OperationBase = require('./operation').OperationBase;
const updateDocuments = require('./common_functions').updateDocuments;
const hasAtomicOperators = require('../utils').hasAtomicOperators;
class UpdateOneOperation extends OperationBase {
constructor(collection, filter, update, options) {
super(options);
if (!hasAtomicOperators(update)) {
throw new TypeError('Update document requires atomic operators');
}
this.collection = collection;
this.filter = filter;
this.update = update;

View File

@@ -14,7 +14,8 @@ class ValidateCollectionOperation extends CommandOperation {
}
super(admin.s.db, options, null, command);
this.collectionName = collectionName;
this.collectionName;
}
execute(callback) {