SERVER-107857 Enforce no-var rule in shell js files (#38826)
GitOrigin-RevId: a5ddaed91d581616e338903acdeb55c2c1978b12
This commit is contained in:
parent
a0d81e9b5c
commit
bea81b2b05
@ -390,7 +390,11 @@ export default [
|
||||
},
|
||||
{
|
||||
// Shell-specific: extra strict!
|
||||
files: ["jstests/core/js/**", "jstests/noPassthrough/shell/**"],
|
||||
files: [
|
||||
"jstests/core/js/**",
|
||||
"jstests/noPassthrough/shell/**",
|
||||
"src/mongo/shell/**",
|
||||
],
|
||||
rules: {
|
||||
"no-var": 2,
|
||||
},
|
||||
|
||||
@ -23,13 +23,13 @@ function MongoBridge(options) {
|
||||
throw new Error('Missing required field "dest"');
|
||||
}
|
||||
|
||||
var hostName = options.hostName || 'localhost';
|
||||
let hostName = options.hostName || 'localhost';
|
||||
|
||||
this.dest = options.dest;
|
||||
this.port = options.port || allocatePort();
|
||||
|
||||
// The connection used by a test for running commands against the mongod or mongos process.
|
||||
var userConn;
|
||||
let userConn;
|
||||
|
||||
// copy the enableTestCommands field from TestData since this can be
|
||||
// changed in the middle of a test. This is the same value that
|
||||
@ -39,11 +39,11 @@ function MongoBridge(options) {
|
||||
this._testCommandsEnabledAtInit = jsTest.options().enableTestCommands;
|
||||
|
||||
// A separate (hidden) connection for configuring the mongobridge process.
|
||||
var controlConn;
|
||||
let controlConn;
|
||||
|
||||
// Start the mongobridge on port 'this.port' routing network traffic to 'this.dest'.
|
||||
var args = ['mongobridge', '--port', this.port, '--dest', this.dest];
|
||||
var keysToSkip = [
|
||||
let args = ['mongobridge', '--port', this.port, '--dest', this.dest];
|
||||
let keysToSkip = [
|
||||
'dest',
|
||||
'hostName',
|
||||
'port',
|
||||
@ -55,7 +55,7 @@ function MongoBridge(options) {
|
||||
return;
|
||||
}
|
||||
|
||||
var value = options[key];
|
||||
let value = options[key];
|
||||
if (value === null || value === undefined) {
|
||||
throw new Error("Value '" + value + "' for '" + key + "' option is ambiguous; specify" +
|
||||
" {flag: ''} to add --flag command line options'");
|
||||
@ -67,7 +67,7 @@ function MongoBridge(options) {
|
||||
}
|
||||
});
|
||||
|
||||
var pid = _startMongoProgram.apply(null, args);
|
||||
let pid = _startMongoProgram.apply(null, args);
|
||||
|
||||
/**
|
||||
* Initializes the mongo shell's connections to the mongobridge process. Throws an error if the
|
||||
@ -86,7 +86,7 @@ function MongoBridge(options) {
|
||||
* bridge.connectToBridge();
|
||||
*/
|
||||
this.connectToBridge = function connectToBridge() {
|
||||
var failedToStart = false;
|
||||
let failedToStart = false;
|
||||
assert.soon(() => {
|
||||
if (!checkProgram(pid).alive) {
|
||||
failedToStart = true;
|
||||
@ -176,7 +176,7 @@ function MongoBridge(options) {
|
||||
bridges.forEach(checkTestCommandsEnabled("acceptConnectionsFrom"));
|
||||
|
||||
bridges.forEach(bridge => {
|
||||
var res = runBridgeCommand(controlConn, 'acceptConnectionsFrom', {host: bridge.dest});
|
||||
let res = runBridgeCommand(controlConn, 'acceptConnectionsFrom', {host: bridge.dest});
|
||||
assert.commandWorked(res,
|
||||
'failed to configure the mongobridge listening on port ' +
|
||||
this.port + ' to accept new connections from ' + bridge.dest);
|
||||
@ -197,7 +197,7 @@ function MongoBridge(options) {
|
||||
bridges.forEach(checkTestCommandsEnabled("rejectConnectionsFrom"));
|
||||
|
||||
bridges.forEach(bridge => {
|
||||
var res = runBridgeCommand(controlConn, 'rejectConnectionsFrom', {host: bridge.dest});
|
||||
let res = runBridgeCommand(controlConn, 'rejectConnectionsFrom', {host: bridge.dest});
|
||||
assert.commandWorked(res,
|
||||
'failed to configure the mongobridge listening on port ' +
|
||||
this.port + ' to hang up connections from ' + bridge.dest);
|
||||
@ -219,7 +219,7 @@ function MongoBridge(options) {
|
||||
bridges.forEach(checkTestCommandsEnabled("delayMessagesFrom"));
|
||||
|
||||
bridges.forEach(bridge => {
|
||||
var res = runBridgeCommand(controlConn, 'delayMessagesFrom', {
|
||||
let res = runBridgeCommand(controlConn, 'delayMessagesFrom', {
|
||||
host: bridge.dest,
|
||||
delay: delay,
|
||||
});
|
||||
@ -245,7 +245,7 @@ function MongoBridge(options) {
|
||||
bridges.forEach(checkTestCommandsEnabled("discardMessagesFrom"));
|
||||
|
||||
bridges.forEach(bridge => {
|
||||
var res = runBridgeCommand(controlConn, 'discardMessagesFrom', {
|
||||
let res = runBridgeCommand(controlConn, 'discardMessagesFrom', {
|
||||
host: bridge.dest,
|
||||
loss: lossProbability,
|
||||
});
|
||||
@ -267,7 +267,7 @@ function MongoBridge(options) {
|
||||
if (target.hasOwnProperty(property)) {
|
||||
return target[property];
|
||||
}
|
||||
var value = userConn[property];
|
||||
let value = userConn[property];
|
||||
if (typeof value === 'function') {
|
||||
return value.bind(userConn);
|
||||
}
|
||||
@ -300,13 +300,13 @@ function runBridgeCommand(conn, cmdName, cmdArgs) {
|
||||
// The wire version of this mongobridge is detected as the wire version of the corresponding
|
||||
// mongod or mongos process because the message is simply forwarded to that process.
|
||||
// Create a new Object with 'cmdName' as the first key and $forBridge=true.
|
||||
var cmdObj = {};
|
||||
let cmdObj = {};
|
||||
cmdObj[cmdName] = 1;
|
||||
cmdObj.$forBridge = true;
|
||||
Object.extend(cmdObj, cmdArgs);
|
||||
|
||||
var dbName = 'test';
|
||||
var noQueryOptions = 0;
|
||||
let dbName = 'test';
|
||||
let noQueryOptions = 0;
|
||||
return conn.runCommand(dbName, cmdObj, noQueryOptions);
|
||||
}
|
||||
|
||||
|
||||
@ -1,20 +1,20 @@
|
||||
|
||||
// Batch types
|
||||
var NONE = 0;
|
||||
var INSERT = 1;
|
||||
var UPDATE = 2;
|
||||
var REMOVE = 3;
|
||||
let NONE = 0;
|
||||
let INSERT = 1;
|
||||
let UPDATE = 2;
|
||||
let REMOVE = 3;
|
||||
|
||||
// Error codes
|
||||
var UNKNOWN_ERROR = 8;
|
||||
var WRITE_CONCERN_FAILED = 64;
|
||||
var UNKNOWN_REPL_WRITE_CONCERN = 79;
|
||||
var NOT_MASTER = 10107;
|
||||
let UNKNOWN_ERROR = 8;
|
||||
let WRITE_CONCERN_FAILED = 64;
|
||||
let UNKNOWN_REPL_WRITE_CONCERN = 79;
|
||||
let NOT_MASTER = 10107;
|
||||
|
||||
/**
|
||||
* Helper function to define properties
|
||||
*/
|
||||
var defineReadOnlyProperty = function(self, name, value) {
|
||||
let defineReadOnlyProperty = function(self, name, value) {
|
||||
Object.defineProperty(self, name, {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
@ -34,12 +34,12 @@ var defineReadOnlyProperty = function(self, name, value) {
|
||||
*/
|
||||
function WriteConcern(wValue, wTimeout, jValue) {
|
||||
if (!(this instanceof WriteConcern)) {
|
||||
var writeConcern = Object.create(WriteConcern.prototype);
|
||||
let writeConcern = Object.create(WriteConcern.prototype);
|
||||
WriteConcern.apply(writeConcern, arguments);
|
||||
return writeConcern;
|
||||
}
|
||||
|
||||
var opts = {};
|
||||
let opts = {};
|
||||
if (typeof wValue == 'object') {
|
||||
if (arguments.length == 1)
|
||||
opts = Object.merge(wValue);
|
||||
@ -158,7 +158,7 @@ function WriteResult(bulkResult, singleBatchType, writeConcern) {
|
||||
* @return {string}
|
||||
*/
|
||||
this.tojson = function(indent, nolint) {
|
||||
var result = {};
|
||||
let result = {};
|
||||
|
||||
if (singleBatchType == INSERT) {
|
||||
result.nInserted = this.nInserted;
|
||||
@ -273,9 +273,9 @@ function BulkWriteResult(bulkResult, singleBatchType, writeConcern) {
|
||||
return bulkResult.writeConcernErrors[0];
|
||||
} else {
|
||||
// Combine the errors
|
||||
var errmsg = "";
|
||||
for (var i = 0; i < bulkResult.writeConcernErrors.length; i++) {
|
||||
var err = bulkResult.writeConcernErrors[i];
|
||||
let errmsg = "";
|
||||
for (let i = 0; i < bulkResult.writeConcernErrors.length; i++) {
|
||||
let err = bulkResult.writeConcernErrors[i];
|
||||
errmsg = errmsg + err.errmsg;
|
||||
// TODO: Something better
|
||||
if (i != bulkResult.writeConcernErrors.length - 1) {
|
||||
@ -313,15 +313,15 @@ function BulkWriteResult(bulkResult, singleBatchType, writeConcern) {
|
||||
this.toError = function() {
|
||||
if (this.hasErrors()) {
|
||||
// Create a combined error message
|
||||
var message = "";
|
||||
var numWriteErrors = this.getWriteErrorCount();
|
||||
let message = "";
|
||||
let numWriteErrors = this.getWriteErrorCount();
|
||||
if (numWriteErrors == 1) {
|
||||
message += "write error at item " + this.getWriteErrors()[0].index;
|
||||
} else if (numWriteErrors > 1) {
|
||||
message += numWriteErrors + " write errors";
|
||||
}
|
||||
|
||||
var hasWCError = this.hasWriteConcernError();
|
||||
let hasWCError = this.hasWriteConcernError();
|
||||
if (numWriteErrors > 0 && hasWCError) {
|
||||
message += " and ";
|
||||
}
|
||||
@ -376,7 +376,7 @@ function BulkWriteError(bulkResult, singleBatchType, writeConcern, message) {
|
||||
BulkWriteError.prototype = Object.create(Error.prototype);
|
||||
BulkWriteError.prototype.constructor = BulkWriteError;
|
||||
|
||||
var getEmptyBulkResult = function() {
|
||||
let getEmptyBulkResult = function() {
|
||||
return {
|
||||
writeErrors: [],
|
||||
writeConcernErrors: [],
|
||||
@ -509,7 +509,7 @@ WriteConcernError.prototype.constructor = WriteConcernError;
|
||||
* Keeps the state of an unordered batch so we can rewrite the results
|
||||
* correctly after command execution
|
||||
*/
|
||||
var Batch = function(batchType, originalZeroIndex) {
|
||||
let Batch = function(batchType, originalZeroIndex) {
|
||||
this.originalZeroIndex = originalZeroIndex;
|
||||
this.batchType = batchType;
|
||||
this.operations = [];
|
||||
@ -518,37 +518,37 @@ var Batch = function(batchType, originalZeroIndex) {
|
||||
/***********************************************************
|
||||
* Wraps the operations done for the batch
|
||||
***********************************************************/
|
||||
var Bulk = function(collection, ordered) {
|
||||
var self = this;
|
||||
var coll = collection;
|
||||
var executed = false;
|
||||
let Bulk = function(collection, ordered) {
|
||||
let self = this;
|
||||
let coll = collection;
|
||||
let executed = false;
|
||||
|
||||
// Set max byte size
|
||||
var maxBatchSizeBytes = 1024 * 1024 * 16;
|
||||
var maxNumberOfDocsInBatch = 1000;
|
||||
var idFieldOverhead = Object.bsonsize({_id: ObjectId()}) - Object.bsonsize({});
|
||||
var writeConcern = null;
|
||||
var rawData = null;
|
||||
var letParams = null;
|
||||
var currentOp;
|
||||
let maxBatchSizeBytes = 1024 * 1024 * 16;
|
||||
let maxNumberOfDocsInBatch = 1000;
|
||||
let idFieldOverhead = Object.bsonsize({_id: ObjectId()}) - Object.bsonsize({});
|
||||
let writeConcern = null;
|
||||
let rawData = null;
|
||||
let letParams = null;
|
||||
let currentOp;
|
||||
|
||||
// Final results
|
||||
var bulkResult = getEmptyBulkResult();
|
||||
let bulkResult = getEmptyBulkResult();
|
||||
|
||||
// Current batch
|
||||
var currentBatch = null;
|
||||
var currentIndex = 0;
|
||||
var currentBatchSize = 0;
|
||||
var currentBatchSizeBytes = 0;
|
||||
var batches = [];
|
||||
let currentBatch = null;
|
||||
let currentIndex = 0;
|
||||
let currentBatchSize = 0;
|
||||
let currentBatchSizeBytes = 0;
|
||||
let batches = [];
|
||||
|
||||
var defineBatchTypeCounter = function(self, name, type) {
|
||||
let defineBatchTypeCounter = function(self, name, type) {
|
||||
Object.defineProperty(self, name, {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
var counter = 0;
|
||||
let counter = 0;
|
||||
|
||||
for (var i = 0; i < batches.length; i++) {
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
if (batches[i].batchType == type) {
|
||||
counter += batches[i].operations.length;
|
||||
}
|
||||
@ -585,7 +585,7 @@ var Bulk = function(collection, ordered) {
|
||||
return batches;
|
||||
};
|
||||
|
||||
var finalizeBatch = function(newDocType) {
|
||||
let finalizeBatch = function(newDocType) {
|
||||
// Save the batch to the execution stack
|
||||
batches.push(currentBatch);
|
||||
|
||||
@ -598,12 +598,12 @@ var Bulk = function(collection, ordered) {
|
||||
};
|
||||
|
||||
// Add to internal list of documents
|
||||
var addToOperationsList = function(docType, document) {
|
||||
let addToOperationsList = function(docType, document) {
|
||||
if (Array.isArray(document))
|
||||
throw Error("operation passed in cannot be an Array");
|
||||
|
||||
// Get the bsonSize
|
||||
var bsonSize = Object.bsonsize(document);
|
||||
let bsonSize = Object.bsonsize(document);
|
||||
|
||||
// If an _id will be added to the insert, adjust the bsonSize
|
||||
if (docType === INSERT && documentNeedsId(document)) {
|
||||
@ -634,7 +634,7 @@ var Bulk = function(collection, ordered) {
|
||||
* @param obj {Object} the document to check if an _id is present
|
||||
* @returns true if the document needs an _id and false otherwise
|
||||
*/
|
||||
var documentNeedsId = function(obj) {
|
||||
function documentNeedsId(obj) {
|
||||
return typeof (obj._id) == "undefined" && !Array.isArray(obj);
|
||||
};
|
||||
|
||||
@ -642,11 +642,11 @@ var Bulk = function(collection, ordered) {
|
||||
* @return {Object} a new document with an _id: ObjectId if _id is not present.
|
||||
* Otherwise, returns the same object passed.
|
||||
*/
|
||||
var addIdIfNeeded = function(obj) {
|
||||
let addIdIfNeeded = function(obj) {
|
||||
if (documentNeedsId(obj)) {
|
||||
var tmp = obj; // don't want to modify input
|
||||
let tmp = obj; // don't want to modify input
|
||||
obj = {_id: new ObjectId()};
|
||||
for (var key in tmp) {
|
||||
for (let key in tmp) {
|
||||
obj[key] = tmp[key];
|
||||
}
|
||||
}
|
||||
@ -665,12 +665,12 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
//
|
||||
// Find based operations
|
||||
var findOperations = {
|
||||
const findOperations = {
|
||||
update: function(updateDocument) {
|
||||
// Set the top value for the update 0 = multi true, 1 = multi false
|
||||
var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
|
||||
let upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
|
||||
// Establish the update command
|
||||
var document = {q: currentOp.selector, u: updateDocument, multi: true, upsert: upsert};
|
||||
let document = {q: currentOp.selector, u: updateDocument, multi: true, upsert: upsert};
|
||||
|
||||
// Copy over the hint, if we have one.
|
||||
if (currentOp.hasOwnProperty('hint')) {
|
||||
@ -695,9 +695,9 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
updateOne: function(updateDocument) {
|
||||
// Set the top value for the update 0 = multi true, 1 = multi false
|
||||
var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
|
||||
let upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
|
||||
// Establish the update command
|
||||
var document = {q: currentOp.selector, u: updateDocument, multi: false, upsert: upsert};
|
||||
let document = {q: currentOp.selector, u: updateDocument, multi: false, upsert: upsert};
|
||||
|
||||
// Copy over the sort, if we have one.
|
||||
if (currentOp.hasOwnProperty('sort')) {
|
||||
@ -751,7 +751,7 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
removeOne: function() {
|
||||
// Establish the removeOne command
|
||||
var document = {q: currentOp.selector, limit: 1};
|
||||
let document = {q: currentOp.selector, limit: 1};
|
||||
|
||||
// Copy over the collation, if we have one.
|
||||
if (currentOp.hasOwnProperty('collation')) {
|
||||
@ -766,7 +766,7 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
remove: function() {
|
||||
// Establish the remove command
|
||||
var document = {q: currentOp.selector, limit: 0};
|
||||
let document = {q: currentOp.selector, limit: 0};
|
||||
|
||||
// Copy over the collation, if we have one.
|
||||
if (currentOp.hasOwnProperty('collation')) {
|
||||
@ -812,7 +812,7 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
//
|
||||
// Merge write command result into aggregated results object
|
||||
var mergeBatchResults = function(batch, bulkResult, result) {
|
||||
let mergeBatchResults = function(batch, bulkResult, result) {
|
||||
// If we have an insert Batch type
|
||||
if (batch.batchType == INSERT) {
|
||||
bulkResult.nInserted = bulkResult.nInserted + result.n;
|
||||
@ -823,13 +823,13 @@ var Bulk = function(collection, ordered) {
|
||||
bulkResult.nRemoved = bulkResult.nRemoved + result.n;
|
||||
}
|
||||
|
||||
var nUpserted = 0;
|
||||
let nUpserted = 0;
|
||||
|
||||
// We have an array of upserted values, we need to rewrite the indexes
|
||||
if (Array.isArray(result.upserted)) {
|
||||
nUpserted = result.upserted.length;
|
||||
|
||||
for (var i = 0; i < result.upserted.length; i++) {
|
||||
for (let i = 0; i < result.upserted.length; i++) {
|
||||
bulkResult.upserted.push({
|
||||
index: result.upserted[i].index + batch.originalZeroIndex,
|
||||
_id: result.upserted[i]._id
|
||||
@ -853,14 +853,14 @@ var Bulk = function(collection, ordered) {
|
||||
}
|
||||
|
||||
if (Array.isArray(result.writeErrors)) {
|
||||
for (var i = 0; i < result.writeErrors.length; i++) {
|
||||
var writeError = {
|
||||
for (let i = 0; i < result.writeErrors.length; i++) {
|
||||
let writeError = {
|
||||
index: batch.originalZeroIndex + result.writeErrors[i].index,
|
||||
code: result.writeErrors[i].code,
|
||||
errmsg: result.writeErrors[i].errmsg,
|
||||
op: batch.operations[result.writeErrors[i].index]
|
||||
};
|
||||
var errInfo = result.writeErrors[i].errInfo;
|
||||
let errInfo = result.writeErrors[i].errInfo;
|
||||
if (errInfo) {
|
||||
writeError['errInfo'] = errInfo;
|
||||
}
|
||||
@ -876,14 +876,14 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
//
|
||||
// Constructs the write batch command.
|
||||
var buildBatchCmd = function(batch) {
|
||||
var cmd = null;
|
||||
let buildBatchCmd = function(batch) {
|
||||
let cmd = null;
|
||||
|
||||
// Generate the right update
|
||||
if (batch.batchType == UPDATE) {
|
||||
cmd = {update: coll.getName(), updates: batch.operations, ordered: ordered};
|
||||
} else if (batch.batchType == INSERT) {
|
||||
var transformedInserts = [];
|
||||
let transformedInserts = [];
|
||||
batch.operations.forEach(function(insertDoc) {
|
||||
transformedInserts.push(addIdIfNeeded(insertDoc));
|
||||
});
|
||||
@ -926,9 +926,9 @@ var Bulk = function(collection, ordered) {
|
||||
|
||||
//
|
||||
// Execute the batch
|
||||
var executeBatch = function(batch) {
|
||||
var result = null;
|
||||
var cmd = buildBatchCmd(batch);
|
||||
let executeBatch = function(batch) {
|
||||
let result = null;
|
||||
let cmd = buildBatchCmd(batch);
|
||||
|
||||
// Run the command (may throw)
|
||||
result = collection.runCommand(cmd);
|
||||
@ -957,10 +957,10 @@ var Bulk = function(collection, ordered) {
|
||||
batches.push(currentBatch);
|
||||
|
||||
// Total number of batches to execute
|
||||
var totalNumberToExecute = batches.length;
|
||||
let totalNumberToExecute = batches.length;
|
||||
|
||||
// Execute all the batches
|
||||
for (var i = 0; i < batches.length; i++) {
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
// Execute the batch
|
||||
executeBatch(batches[i]);
|
||||
|
||||
@ -1002,8 +1002,8 @@ var Bulk = function(collection, ordered) {
|
||||
throw Error("Explained bulk operations must consist of exactly 1 batch");
|
||||
}
|
||||
|
||||
var explainBatch = batches[0];
|
||||
var writeCmd = buildBatchCmd(explainBatch);
|
||||
let explainBatch = batches[0];
|
||||
let writeCmd = buildBatchCmd(explainBatch);
|
||||
return {"explain": writeCmd, "verbosity": verbosity};
|
||||
};
|
||||
};
|
||||
|
||||
@ -40,7 +40,7 @@ DBCollection.prototype.getName = function() {
|
||||
};
|
||||
|
||||
DBCollection.prototype.help = function() {
|
||||
var shortName = this.getName();
|
||||
let shortName = this.getName();
|
||||
print("DBCollection help");
|
||||
print("\tdb." + shortName + ".find().help() - show DBCursor help");
|
||||
print(
|
||||
@ -189,7 +189,7 @@ DBCollection.prototype.getDB = function() {
|
||||
};
|
||||
|
||||
DBCollection.prototype._makeCommand = function(cmd, params) {
|
||||
var c = {};
|
||||
let c = {};
|
||||
c[cmd] = this.getName();
|
||||
if (params)
|
||||
Object.extend(c, params);
|
||||
@ -219,7 +219,7 @@ DBCollection.prototype._massageObject = function(q) {
|
||||
if (!q)
|
||||
return {};
|
||||
|
||||
var type = typeof q;
|
||||
let type = typeof q;
|
||||
|
||||
if (type == "function")
|
||||
return {$where: q};
|
||||
@ -246,7 +246,7 @@ DBCollection.prototype.find = function(filter, projection, limit, skip, batchSiz
|
||||
// Verify that API version parameters are not supplied via the shell helper.
|
||||
assert.noAPIParams(options);
|
||||
|
||||
var cursor = new DBQuery(this._mongo,
|
||||
let cursor = new DBQuery(this._mongo,
|
||||
this._db,
|
||||
this,
|
||||
this._fullName,
|
||||
@ -286,7 +286,7 @@ DBCollection.prototype.findOneWithRawData = function(filter) {
|
||||
|
||||
DBCollection.prototype.findOne = function(
|
||||
filter, projection, options, readConcern, collation, rawData) {
|
||||
var cursor =
|
||||
let cursor =
|
||||
this.find(filter, projection, -1 /* limit */, 0 /* skip*/, 0 /* batchSize */, options);
|
||||
|
||||
if (readConcern) {
|
||||
@ -303,7 +303,7 @@ DBCollection.prototype.findOne = function(
|
||||
|
||||
if (!cursor.hasNext())
|
||||
return null;
|
||||
var ret = cursor.next();
|
||||
let ret = cursor.next();
|
||||
if (cursor.hasNext())
|
||||
throw Error("findOne has more than 1 result!");
|
||||
if (ret.$err)
|
||||
@ -320,10 +320,10 @@ DBCollection.prototype.insert = function(obj, options) {
|
||||
|
||||
options = typeof (options) === 'undefined' ? {} : options;
|
||||
|
||||
var flags = 0;
|
||||
let flags = 0;
|
||||
|
||||
var wc = undefined;
|
||||
var rawData = undefined;
|
||||
let wc = undefined;
|
||||
let rawData = undefined;
|
||||
if (options === undefined) {
|
||||
// do nothing
|
||||
} else if (typeof (options) == 'object') {
|
||||
@ -343,18 +343,18 @@ DBCollection.prototype.insert = function(obj, options) {
|
||||
}
|
||||
|
||||
// 1 = continueOnError, which is synonymous with unordered in the write commands/bulk-api
|
||||
var ordered = ((flags & 1) == 0);
|
||||
let ordered = ((flags & 1) == 0);
|
||||
|
||||
if (!wc)
|
||||
wc = this._createWriteConcern(options);
|
||||
|
||||
var result = undefined;
|
||||
let result = undefined;
|
||||
|
||||
// Bit 1 of option flag is continueOnError. Bit 0 (stop on error) is the default.
|
||||
var bulk = ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
let bulk = ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
if (rawData)
|
||||
bulk.setRawData(rawData);
|
||||
var isMultiInsert = Array.isArray(obj);
|
||||
let isMultiInsert = Array.isArray(obj);
|
||||
|
||||
if (isMultiInsert) {
|
||||
obj.forEach(function(doc) {
|
||||
@ -389,15 +389,15 @@ DBCollection.prototype._parseRemove = function(t, justOne) {
|
||||
if (undefined === t)
|
||||
throw Error("remove needs a query");
|
||||
|
||||
var query = this._massageObject(t);
|
||||
let query = this._massageObject(t);
|
||||
|
||||
var wc = undefined;
|
||||
var collation = undefined;
|
||||
let wc = undefined;
|
||||
let collation = undefined;
|
||||
let letParams = undefined;
|
||||
let rawData = undefined;
|
||||
|
||||
if (typeof (justOne) === "object") {
|
||||
var opts = justOne;
|
||||
let opts = justOne;
|
||||
wc = opts.writeConcern;
|
||||
justOne = opts.justOne;
|
||||
collation = opts.collation;
|
||||
@ -426,16 +426,16 @@ DBCollection.prototype._parseRemove = function(t, justOne) {
|
||||
// Returns a WriteResult if write command succeeded, but may contain write errors.
|
||||
// Returns a WriteCommandError if the write command responded with ok:0.
|
||||
DBCollection.prototype.remove = function(t, justOne) {
|
||||
var parsed = this._parseRemove(t, justOne);
|
||||
var query = parsed.query;
|
||||
var justOne = parsed.justOne;
|
||||
var wc = parsed.wc;
|
||||
var collation = parsed.collation;
|
||||
var letParams = parsed.let;
|
||||
let parsed = this._parseRemove(t, justOne);
|
||||
let query = parsed.query;
|
||||
justOne = parsed.justOne;
|
||||
let wc = parsed.wc;
|
||||
let collation = parsed.collation;
|
||||
let letParams = parsed.let;
|
||||
let rawData = parsed.rawData;
|
||||
|
||||
var result = undefined;
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let result = undefined;
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
if (letParams) {
|
||||
bulk.setLetParams(letParams);
|
||||
@ -445,7 +445,7 @@ DBCollection.prototype.remove = function(t, justOne) {
|
||||
bulk.setRawData(rawData);
|
||||
}
|
||||
|
||||
var removeOp = bulk.find(query);
|
||||
let removeOp = bulk.find(query);
|
||||
|
||||
if (collation) {
|
||||
removeOp.collation(collation);
|
||||
@ -484,9 +484,9 @@ DBCollection.prototype._parseUpdate = function(query, updateSpec, upsert, multi)
|
||||
if (!updateSpec)
|
||||
throw Error("need an update object or pipeline");
|
||||
|
||||
var wc = undefined;
|
||||
var collation = undefined;
|
||||
var arrayFilters = undefined;
|
||||
let wc = undefined;
|
||||
let collation = undefined;
|
||||
let arrayFilters = undefined;
|
||||
let hint = undefined;
|
||||
let letParams = undefined;
|
||||
let rawData = undefined;
|
||||
@ -498,7 +498,7 @@ DBCollection.prototype._parseUpdate = function(query, updateSpec, upsert, multi)
|
||||
"upsert and multi with an object.");
|
||||
}
|
||||
|
||||
var opts = upsert;
|
||||
let opts = upsert;
|
||||
multi = opts.multi;
|
||||
wc = opts.writeConcern;
|
||||
upsert = opts.upsert;
|
||||
@ -538,20 +538,20 @@ DBCollection.prototype._parseUpdate = function(query, updateSpec, upsert, multi)
|
||||
// Returns a WriteResult if write command succeeded, but may contain write errors.
|
||||
// Returns a WriteCommandError if the write command responded with ok:0.
|
||||
DBCollection.prototype.update = function(query, updateSpec, upsert, multi) {
|
||||
var parsed = this._parseUpdate(query, updateSpec, upsert, multi);
|
||||
var query = parsed.query;
|
||||
var updateSpec = parsed.updateSpec;
|
||||
let parsed = this._parseUpdate(query, updateSpec, upsert, multi);
|
||||
query = parsed.query;
|
||||
updateSpec = parsed.updateSpec;
|
||||
const hint = parsed.hint;
|
||||
var upsert = parsed.upsert;
|
||||
var multi = parsed.multi;
|
||||
var wc = parsed.wc;
|
||||
var collation = parsed.collation;
|
||||
var arrayFilters = parsed.arrayFilters;
|
||||
upsert = parsed.upsert;
|
||||
multi = parsed.multi;
|
||||
let wc = parsed.wc;
|
||||
let collation = parsed.collation;
|
||||
let arrayFilters = parsed.arrayFilters;
|
||||
let letParams = parsed.let;
|
||||
let rawData = parsed.rawData;
|
||||
|
||||
var result = undefined;
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let result = undefined;
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
if (letParams) {
|
||||
bulk.setLetParams(letParams);
|
||||
@ -561,7 +561,7 @@ DBCollection.prototype.update = function(query, updateSpec, upsert, multi) {
|
||||
bulk.setRawData(rawData);
|
||||
}
|
||||
|
||||
var updateOp = bulk.find(query);
|
||||
let updateOp = bulk.find(query);
|
||||
|
||||
if (hint) {
|
||||
updateOp.hint(hint);
|
||||
@ -620,9 +620,9 @@ DBCollection.prototype.save = function(obj, opts) {
|
||||
};
|
||||
|
||||
DBCollection.prototype._genIndexName = function(keys) {
|
||||
var name = "";
|
||||
for (var k in keys) {
|
||||
var v = keys[k];
|
||||
let name = "";
|
||||
for (let k in keys) {
|
||||
let v = keys[k];
|
||||
if (typeof v == "function")
|
||||
continue;
|
||||
|
||||
@ -636,7 +636,7 @@ DBCollection.prototype._genIndexName = function(keys) {
|
||||
};
|
||||
|
||||
DBCollection.prototype._indexSpec = function(keys, options) {
|
||||
var ret = {ns: this._fullName, key: keys, name: this._genIndexName(keys)};
|
||||
let ret = {ns: this._fullName, key: keys, name: this._genIndexName(keys)};
|
||||
|
||||
if (!options) {
|
||||
} else if (typeof (options) == "string")
|
||||
@ -649,8 +649,8 @@ DBCollection.prototype._indexSpec = function(keys, options) {
|
||||
throw new Error("Index options that are supplied in array form may only specify" +
|
||||
" three values: name, unique, dropDups");
|
||||
}
|
||||
var nb = 0;
|
||||
for (var i = 0; i < options.length; i++) {
|
||||
let nb = 0;
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
if (typeof (options[i]) == "string")
|
||||
ret.name = options[i];
|
||||
else if (typeof (options[i]) == "boolean") {
|
||||
@ -690,12 +690,12 @@ DBCollection.prototype.createIndexes = function(keys, options, commitQuorum, cmd
|
||||
throw new Error("createIndexes first argument should be an array");
|
||||
}
|
||||
|
||||
var indexSpecs = Array(keys.length);
|
||||
for (var i = 0; i < indexSpecs.length; i++) {
|
||||
let indexSpecs = Array(keys.length);
|
||||
for (let i = 0; i < indexSpecs.length; i++) {
|
||||
indexSpecs[i] = this._indexSpec(keys[i], options);
|
||||
}
|
||||
|
||||
for (var i = 0; i < indexSpecs.length; i++) {
|
||||
for (let i = 0; i < indexSpecs.length; i++) {
|
||||
delete (indexSpecs[i].ns); // ns is passed to the first element in the command.
|
||||
}
|
||||
|
||||
@ -740,8 +740,8 @@ DBCollection.prototype.drop = function(options = {}) {
|
||||
};
|
||||
|
||||
DBCollection.prototype.findAndModify = function(args) {
|
||||
var cmd = {findandmodify: this.getName()};
|
||||
for (var key in args) {
|
||||
let cmd = {findandmodify: this.getName()};
|
||||
for (let key in args) {
|
||||
cmd[key] = args[key];
|
||||
}
|
||||
|
||||
@ -758,7 +758,7 @@ DBCollection.prototype.findAndModify = function(args) {
|
||||
}
|
||||
}
|
||||
|
||||
var ret = this._db.runCommand(cmd);
|
||||
let ret = this._db.runCommand(cmd);
|
||||
if (!ret.ok) {
|
||||
if (ret.errmsg == "No matching object found") {
|
||||
return null;
|
||||
@ -794,24 +794,24 @@ DBCollection.prototype.validate = function(options) {
|
||||
return "expected optional options to be of the following format: {full: <bool>, background: <bool>}.";
|
||||
}
|
||||
|
||||
var cmd = {validate: this.getName()};
|
||||
let cmd = {validate: this.getName()};
|
||||
Object.assign(cmd, options || {});
|
||||
|
||||
var res = this._db.runCommand(cmd);
|
||||
let res = this._db.runCommand(cmd);
|
||||
|
||||
if (typeof (res.valid) == 'undefined') {
|
||||
// old-style format just put everything in a string. Now using proper fields
|
||||
|
||||
res.valid = false;
|
||||
|
||||
var raw = res.result || res.raw;
|
||||
let raw = res.result || res.raw;
|
||||
|
||||
if (raw) {
|
||||
var str = "-" + tojson(raw);
|
||||
let str = "-" + tojson(raw);
|
||||
res.valid = !(str.match(/exception/) || str.match(/corrupt/));
|
||||
|
||||
var p = /lastExtentSize:(\d+)/;
|
||||
var r = p.exec(str);
|
||||
let p = /lastExtentSize:(\d+)/;
|
||||
let r = p.exec(str);
|
||||
if (r) {
|
||||
res.lastExtentSize = Number(r[1]);
|
||||
}
|
||||
@ -866,9 +866,9 @@ DBCollection.prototype.getIndexKeys = function(options = {}) {
|
||||
};
|
||||
|
||||
DBCollection.prototype.hashAllDocs = function() {
|
||||
var cmd = {dbhash: 1, collections: [this._shortName]};
|
||||
var res = this._dbCommand(cmd);
|
||||
var hash = res.collections[this._shortName];
|
||||
let cmd = {dbhash: 1, collections: [this._shortName]};
|
||||
let res = this._dbCommand(cmd);
|
||||
let hash = res.collections[this._shortName];
|
||||
assert(hash);
|
||||
assert(typeof (hash) == "string");
|
||||
return hash;
|
||||
@ -899,7 +899,7 @@ DBCollection.prototype.dropIndex = function(index) {
|
||||
"To drop indexes in the collection using '*', use db.collection.dropIndexes()");
|
||||
}
|
||||
|
||||
var res = this._dbCommand("dropIndexes", {index: index});
|
||||
let res = this._dbCommand("dropIndexes", {index: index});
|
||||
return res;
|
||||
};
|
||||
|
||||
@ -911,7 +911,7 @@ DBCollection.prototype._hiddenIndex = function(index, hidden) {
|
||||
|
||||
// Need an extra check for array because 'Array' is an 'object', but not every 'object' is an
|
||||
// 'Array'.
|
||||
var indexField = {};
|
||||
let indexField = {};
|
||||
if (typeof index == "string") {
|
||||
indexField = {name: index, hidden: hidden};
|
||||
} else if (typeof index == "object") {
|
||||
@ -919,8 +919,8 @@ DBCollection.prototype._hiddenIndex = function(index, hidden) {
|
||||
} else {
|
||||
throw new Error("Index must be either the index name or the index specification document");
|
||||
}
|
||||
var cmd = {"collMod": this._shortName, index: indexField};
|
||||
var res = this._db.runCommand(cmd);
|
||||
let cmd = {"collMod": this._shortName, index: indexField};
|
||||
let res = this._db.runCommand(cmd);
|
||||
return res;
|
||||
};
|
||||
|
||||
@ -949,29 +949,29 @@ DBCollection.prototype.stats = function(args) {
|
||||
'use strict';
|
||||
|
||||
// For backwards compatibility with db.collection.stats(scale).
|
||||
var scale = isObject(args) ? args.scale : args;
|
||||
let scale = isObject(args) ? args.scale : args;
|
||||
|
||||
var options = isObject(args) ? args : {};
|
||||
let options = isObject(args) ? args : {};
|
||||
if (options.indexDetailsKey && options.indexDetailsName) {
|
||||
throw new Error('Cannot filter indexDetails on both indexDetailsKey and ' +
|
||||
'indexDetailsName');
|
||||
}
|
||||
// collStats can run on a secondary, so we need to apply readPreference
|
||||
var res = this._db.runReadCommand({collStats: this._shortName, scale: scale});
|
||||
let res = this._db.runReadCommand({collStats: this._shortName, scale: scale});
|
||||
if (!res.ok) {
|
||||
return res;
|
||||
}
|
||||
|
||||
var getIndexName = function(collection, indexKey) {
|
||||
let getIndexName = function(collection, indexKey) {
|
||||
if (!isObject(indexKey))
|
||||
return undefined;
|
||||
let index = collection.getIndexByKey(indexKey);
|
||||
return index?.name;
|
||||
};
|
||||
|
||||
var filterIndexName = options.indexDetailsName || getIndexName(this, options.indexDetailsKey);
|
||||
let filterIndexName = options.indexDetailsName || getIndexName(this, options.indexDetailsKey);
|
||||
|
||||
var updateStats = function(stats, keepIndexDetails, indexName) {
|
||||
let updateStats = function(stats, keepIndexDetails, indexName) {
|
||||
if (!stats.indexDetails)
|
||||
return;
|
||||
if (!keepIndexDetails) {
|
||||
@ -980,7 +980,7 @@ DBCollection.prototype.stats = function(args) {
|
||||
}
|
||||
if (!indexName)
|
||||
return;
|
||||
for (var key in stats.indexDetails) {
|
||||
for (let key in stats.indexDetails) {
|
||||
if (key == indexName)
|
||||
continue;
|
||||
delete stats.indexDetails[key];
|
||||
@ -990,7 +990,7 @@ DBCollection.prototype.stats = function(args) {
|
||||
updateStats(res, options.indexDetails, filterIndexName);
|
||||
|
||||
if (res.sharded) {
|
||||
for (var shardName in res.shards) {
|
||||
for (let shardName in res.shards) {
|
||||
updateStats(res.shards[shardName], options.indexDetails, filterIndexName);
|
||||
}
|
||||
}
|
||||
@ -1007,9 +1007,9 @@ DBCollection.prototype.storageSize = function() {
|
||||
};
|
||||
|
||||
DBCollection.prototype.totalIndexSize = function(verbose) {
|
||||
var stats = this.stats();
|
||||
let stats = this.stats();
|
||||
if (verbose) {
|
||||
for (var ns in stats.indexSizes) {
|
||||
for (let ns in stats.indexSizes) {
|
||||
print(ns + "\t" + stats.indexSizes[ns]);
|
||||
}
|
||||
}
|
||||
@ -1017,8 +1017,8 @@ DBCollection.prototype.totalIndexSize = function(verbose) {
|
||||
};
|
||||
|
||||
DBCollection.prototype.totalSize = function() {
|
||||
var total = this.storageSize();
|
||||
var totalIndexSize = this.totalIndexSize();
|
||||
let total = this.storageSize();
|
||||
let totalIndexSize = this.totalIndexSize();
|
||||
if (totalIndexSize) {
|
||||
total += totalIndexSize;
|
||||
}
|
||||
@ -1037,7 +1037,7 @@ DBCollection.prototype.convertToCapped = function(bytes) {
|
||||
* If the collection does not exists return null.
|
||||
*/
|
||||
DBCollection.prototype.getMetadata = function(params) {
|
||||
var res = this._db.runCommand("listCollections", {filter: {name: this._shortName}, ...params});
|
||||
let res = this._db.runCommand("listCollections", {filter: {name: this._shortName}, ...params});
|
||||
if (res.ok) {
|
||||
const cursor = new DBCommandCursor(this._db, res);
|
||||
if (!cursor.hasNext())
|
||||
@ -1083,7 +1083,7 @@ DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) {
|
||||
};
|
||||
|
||||
DBCollection.prototype.convertToSingleObject = function(valueField) {
|
||||
var z = {};
|
||||
let z = {};
|
||||
this.find().forEach(function(a) {
|
||||
z[a._id] = a[valueField];
|
||||
});
|
||||
@ -1094,7 +1094,7 @@ DBCollection.prototype.convertToSingleObject = function(valueField) {
|
||||
* @param optional object of optional fields;
|
||||
*/
|
||||
DBCollection.prototype.mapReduce = function(map, reduce, optionsOrOutString) {
|
||||
var c = {mapreduce: this._shortName, map: map, reduce: reduce};
|
||||
let c = {mapreduce: this._shortName, map: map, reduce: reduce};
|
||||
assert(optionsOrOutString, "need to supply an optionsOrOutString");
|
||||
|
||||
if (typeof (optionsOrOutString) == "string")
|
||||
@ -1102,7 +1102,7 @@ DBCollection.prototype.mapReduce = function(map, reduce, optionsOrOutString) {
|
||||
else
|
||||
Object.extend(c, optionsOrOutString);
|
||||
|
||||
var output;
|
||||
let output;
|
||||
|
||||
if (c["out"].hasOwnProperty("inline") && c["out"]["inline"] === 1) {
|
||||
// if inline output is specified, we need to apply readPreference on the command
|
||||
@ -1128,10 +1128,10 @@ DBCollection.prototype.tojson = DBCollection.prototype.toString;
|
||||
DBCollection.prototype.shellPrint = DBCollection.prototype.toString;
|
||||
|
||||
DBCollection.autocomplete = function(obj) {
|
||||
var colls = DB.autocomplete(obj.getDB());
|
||||
var ret = [];
|
||||
for (var i = 0; i < colls.length; i++) {
|
||||
var c = colls[i];
|
||||
let colls = DB.autocomplete(obj.getDB());
|
||||
let ret = [];
|
||||
for (let i = 0; i < colls.length; i++) {
|
||||
let c = colls[i];
|
||||
if (c.length <= obj.getName().length)
|
||||
continue;
|
||||
if (c.slice(0, obj.getName().length + 1) != obj.getName() + '.')
|
||||
@ -1159,23 +1159,23 @@ DBCollection.prototype._isSharded = function() {
|
||||
* Prints statistics related to the collection's data distribution
|
||||
*/
|
||||
DBCollection.prototype.getShardDistribution = function() {
|
||||
var config = this.getDB().getSiblingDB("config");
|
||||
let config = this.getDB().getSiblingDB("config");
|
||||
|
||||
if (!this._isSharded()) {
|
||||
print("Collection " + this + " is not sharded.");
|
||||
return;
|
||||
}
|
||||
|
||||
var collStats = this.aggregate({"$collStats": {storageStats: {}}});
|
||||
let collStats = this.aggregate({"$collStats": {storageStats: {}}});
|
||||
|
||||
var totals = {numChunks: 0, size: 0, count: 0};
|
||||
var conciseShardsStats = [];
|
||||
let totals = {numChunks: 0, size: 0, count: 0};
|
||||
let conciseShardsStats = [];
|
||||
|
||||
collStats.forEach(function(extShardStats) {
|
||||
// Extract and store only the relevant subset of the stats for this shard
|
||||
var newVersion = config.collections.countDocuments(
|
||||
let newVersion = config.collections.countDocuments(
|
||||
{_id: extShardStats.ns, timestamp: {$exists: true}}, {limit: 1});
|
||||
var collUuid = config.collections.findOne({_id: extShardStats.ns}).uuid;
|
||||
let collUuid = config.collections.findOne({_id: extShardStats.ns}).uuid;
|
||||
const shardStats = {
|
||||
shardId: extShardStats.shard,
|
||||
host: config.shards.findOne({_id: extShardStats.shard}).host,
|
||||
@ -1190,9 +1190,9 @@ DBCollection.prototype.getShardDistribution = function() {
|
||||
|
||||
print("\nShard " + shardStats.shardId + " at " + shardStats.host);
|
||||
|
||||
var estChunkData =
|
||||
let estChunkData =
|
||||
(shardStats.numChunks == 0) ? 0 : (shardStats.size / shardStats.numChunks);
|
||||
var estChunkCount =
|
||||
let estChunkCount =
|
||||
(shardStats.numChunks == 0) ? 0 : Math.floor(shardStats.count / shardStats.numChunks);
|
||||
print(" data : " + sh._dataFormat(shardStats.size) + " docs : " + shardStats.count +
|
||||
" chunks : " + shardStats.numChunks);
|
||||
@ -1210,9 +1210,9 @@ DBCollection.prototype.getShardDistribution = function() {
|
||||
print(" data : " + sh._dataFormat(totals.size) + " docs : " + totals.count +
|
||||
" chunks : " + totals.numChunks);
|
||||
for (const shardStats of conciseShardsStats) {
|
||||
var estDataPercent =
|
||||
let estDataPercent =
|
||||
(totals.size == 0) ? 0 : (Math.floor(shardStats.size / totals.size * 10000) / 100);
|
||||
var estDocPercent =
|
||||
let estDocPercent =
|
||||
(totals.count == 0) ? 0 : (Math.floor(shardStats.count / totals.count * 10000) / 100);
|
||||
|
||||
print(" Shard " + shardStats.shardId + " contains " + estDataPercent + "% data, " +
|
||||
@ -1231,7 +1231,7 @@ DBCollection.prototype.getShardKey = function() {
|
||||
throw Error("Collection " + this + " is not sharded.");
|
||||
}
|
||||
|
||||
var config = this.getDB().getSiblingDB("config");
|
||||
let config = this.getDB().getSiblingDB("config");
|
||||
const coll = config.collections.findOne({_id: this._fullName});
|
||||
return coll.key;
|
||||
};
|
||||
@ -1252,14 +1252,14 @@ will actually do the splits.
|
||||
*/
|
||||
|
||||
DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) {
|
||||
var stats = this.stats();
|
||||
let stats = this.stats();
|
||||
|
||||
if (!stats.sharded) {
|
||||
print("Collection " + this + " is not sharded.");
|
||||
return;
|
||||
}
|
||||
|
||||
var config = this.getDB().getSiblingDB("config");
|
||||
let config = this.getDB().getSiblingDB("config");
|
||||
|
||||
if (!chunkSize) {
|
||||
chunkSize = config.settings.findOne({_id: "chunksize"}).value;
|
||||
@ -1268,26 +1268,26 @@ DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) {
|
||||
print("Using chunk size of " + chunkSize + "MB");
|
||||
}
|
||||
|
||||
var shardDocs = config.shards.find().toArray();
|
||||
let shardDocs = config.shards.find().toArray();
|
||||
|
||||
var allSplitPoints = {};
|
||||
var numSplits = 0;
|
||||
let allSplitPoints = {};
|
||||
let numSplits = 0;
|
||||
|
||||
for (var i = 0; i < shardDocs.length; i++) {
|
||||
var shardDoc = shardDocs[i];
|
||||
var shard = shardDoc._id;
|
||||
var host = shardDoc.host;
|
||||
var sconn = new Mongo(host);
|
||||
for (let i = 0; i < shardDocs.length; i++) {
|
||||
let shardDoc = shardDocs[i];
|
||||
let shard = shardDoc._id;
|
||||
let host = shardDoc.host;
|
||||
let sconn = new Mongo(host);
|
||||
|
||||
var chunks = config.chunks.find({_id: sh._collRE(this), shard: shard}).toArray();
|
||||
let chunks = config.chunks.find({_id: sh._collRE(this), shard: shard}).toArray();
|
||||
|
||||
print("\nGetting split points for chunks on shard " + shard + " at " + host);
|
||||
|
||||
var splitPoints = [];
|
||||
let splitPoints = [];
|
||||
|
||||
for (var j = 0; j < chunks.length; j++) {
|
||||
var chunk = chunks[j];
|
||||
var result = sconn.getDB("admin").runCommand(
|
||||
for (let j = 0; j < chunks.length; j++) {
|
||||
let chunk = chunks[j];
|
||||
let result = sconn.getDB("admin").runCommand(
|
||||
{splitVector: this + "", min: chunk.min, max: chunk.max, maxChunkSize: chunkSize});
|
||||
if (!result.ok) {
|
||||
print(" Had trouble getting split keys for chunk " + sh._pchunk(chunk) + " :\n");
|
||||
@ -1308,7 +1308,7 @@ DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) {
|
||||
}
|
||||
|
||||
// Get most recent migration
|
||||
var migration = config.changelog.find({what: /^move.*/}).sort({time: -1}).limit(1).toArray();
|
||||
let migration = config.changelog.find({what: /^move.*/}).sort({time: -1}).limit(1).toArray();
|
||||
if (migration.length == 0)
|
||||
print("\nNo migrations found in changelog.");
|
||||
else {
|
||||
@ -1316,9 +1316,9 @@ DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) {
|
||||
print("\nMost recent migration activity was on " + migration.ns + " at " + migration.time);
|
||||
}
|
||||
|
||||
var admin = this.getDB().getSiblingDB("admin");
|
||||
var coll = this;
|
||||
var splitFunction = function() {
|
||||
let admin = this.getDB().getSiblingDB("admin");
|
||||
let coll = this;
|
||||
let splitFunction = function() {
|
||||
// Turn off the balancer, just to be safe
|
||||
print("Turning off balancer...");
|
||||
config.settings.update({_id: "balancer"}, {$set: {stopped: true}}, true);
|
||||
@ -1327,9 +1327,9 @@ DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) {
|
||||
" for recent migrations.");
|
||||
sleep(30000);
|
||||
|
||||
for (var shard in allSplitPoints) {
|
||||
for (var i = 0; i < allSplitPoints[shard].length; i++) {
|
||||
var splitKey = allSplitPoints[shard][i];
|
||||
for (let shard in allSplitPoints) {
|
||||
for (let i = 0; i < allSplitPoints[shard].length; i++) {
|
||||
let splitKey = allSplitPoints[shard][i];
|
||||
print("Splitting at " + tojson(splitKey));
|
||||
printjson(admin.runCommand({split: coll + "", middle: splitKey}));
|
||||
}
|
||||
@ -1363,7 +1363,7 @@ DBCollection.prototype.enableBalancing = function() {
|
||||
throw Error("Collection " + this + " is not sharded.");
|
||||
}
|
||||
|
||||
var adminDb = this.getDB().getSiblingDB("admin");
|
||||
let adminDb = this.getDB().getSiblingDB("admin");
|
||||
const fcvDoc = adminDb.runCommand({
|
||||
getParameter: 1,
|
||||
featureCompatibilityVersion: 1,
|
||||
@ -1375,7 +1375,7 @@ DBCollection.prototype.enableBalancing = function() {
|
||||
return adminDb.runCommand(
|
||||
{configureCollectionBalancing: this._fullName, enableBalancing: true});
|
||||
} else {
|
||||
var configDb = this.getDB().getSiblingDB("config");
|
||||
let configDb = this.getDB().getSiblingDB("config");
|
||||
return assert.commandWorked(
|
||||
configDb.collections.update({_id: this._fullName}, {$set: {"noBalance": false}}));
|
||||
}
|
||||
@ -1391,7 +1391,7 @@ DBCollection.prototype.disableBalancing = function() {
|
||||
if (!this._isSharded()) {
|
||||
throw Error("Collection " + this + " is not sharded.");
|
||||
}
|
||||
var adminDb = this.getDB().getSiblingDB("admin");
|
||||
let adminDb = this.getDB().getSiblingDB("admin");
|
||||
const fcvDoc = adminDb.runCommand({
|
||||
getParameter: 1,
|
||||
featureCompatibilityVersion: 1,
|
||||
@ -1403,7 +1403,7 @@ DBCollection.prototype.disableBalancing = function() {
|
||||
return adminDb.runCommand(
|
||||
{configureCollectionBalancing: this._fullName, enableBalancing: false});
|
||||
} else {
|
||||
var configDb = this.getDB().getSiblingDB("config");
|
||||
let configDb = this.getDB().getSiblingDB("config");
|
||||
return assert.commandWorked(
|
||||
configDb.collections.update({_id: this._fullName}, {$set: {"noBalance": true}}));
|
||||
}
|
||||
@ -1623,9 +1623,9 @@ DBCollection.prototype.estimatedDocumentCount = function(options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.distinct = function(keyString, query, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
var keyStringType = typeof keyString;
|
||||
var queryType = typeof query;
|
||||
let opts = Object.extend({}, options || {});
|
||||
let keyStringType = typeof keyString;
|
||||
let queryType = typeof query;
|
||||
|
||||
if (keyStringType != "string") {
|
||||
throw new Error("The first argument to the distinct command must be a string but was a " +
|
||||
@ -1638,7 +1638,7 @@ DBCollection.prototype.distinct = function(keyString, query, options) {
|
||||
}
|
||||
|
||||
// Distinct command
|
||||
var cmd = {distinct: this.getName(), key: keyString, query: query || {}};
|
||||
let cmd = {distinct: this.getName(), key: keyString, query: query || {}};
|
||||
|
||||
// Set maxTimeMS if provided
|
||||
if (opts.maxTimeMS) {
|
||||
@ -1658,7 +1658,7 @@ DBCollection.prototype.distinct = function(keyString, query, options) {
|
||||
}
|
||||
|
||||
// Execute distinct command
|
||||
var res = this.runReadCommand(cmd);
|
||||
let res = this.runReadCommand(cmd);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, "distinct failed: " + tojson(res));
|
||||
}
|
||||
@ -1722,7 +1722,7 @@ PlanCache.prototype.shellPrint = PlanCache.prototype.toString;
|
||||
* Displays help for a PlanCache object.
|
||||
*/
|
||||
PlanCache.prototype.help = function() {
|
||||
var shortName = this.getName();
|
||||
let shortName = this.getName();
|
||||
print("PlanCache help");
|
||||
print("\tdb." + shortName + ".getPlanCache().help() - show PlanCache help");
|
||||
print("\tdb." + shortName + ".getPlanCache().clear() - " +
|
||||
@ -1749,7 +1749,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort, collati
|
||||
// 'collation'. 'collation' must be non-empty if present.
|
||||
if (typeof (query) == 'object' && projection == undefined && sort == undefined &&
|
||||
collation == undefined) {
|
||||
var keysSorted = Object.keys(query).sort();
|
||||
let keysSorted = Object.keys(query).sort();
|
||||
// Expected keys must be sorted for the comparison to work.
|
||||
if (bsonWoCompare(keysSorted, ['projection', 'query', 'sort']) == 0) {
|
||||
return query;
|
||||
@ -1776,7 +1776,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort, collati
|
||||
throw new Error("cannot pass DBQuery with collation");
|
||||
}
|
||||
|
||||
var queryObj = query._query["query"] || {};
|
||||
let queryObj = query._query["query"] || {};
|
||||
projection = query._fields || {};
|
||||
sort = query._query["orderby"] || {};
|
||||
collation = query._query["collation"] || undefined;
|
||||
@ -1784,7 +1784,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort, collati
|
||||
query = queryObj;
|
||||
}
|
||||
|
||||
var shape = {
|
||||
let shape = {
|
||||
query: query,
|
||||
projection: projection == undefined ? {} : projection,
|
||||
sort: sort == undefined ? {} : sort,
|
||||
@ -1801,7 +1801,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort, collati
|
||||
* Internal function to run command.
|
||||
*/
|
||||
PlanCache.prototype._runCommandThrowOnError = function(cmd, params) {
|
||||
var res = this._collection.runCommand(cmd, params);
|
||||
let res = this._collection.runCommand(cmd, params);
|
||||
if (!res.ok) {
|
||||
throw new Error(res.errmsg);
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
DBCollection.prototype._createWriteConcern = function(options) {
|
||||
// If writeConcern set, use it, else get from collection (which will inherit from db/mongo)
|
||||
var writeConcern = options.writeConcern || this.getWriteConcern();
|
||||
var writeConcernOptions = ['w', 'wtimeout', 'j', 'fsync'];
|
||||
let writeConcern = options.writeConcern || this.getWriteConcern();
|
||||
let writeConcernOptions = ['w', 'wtimeout', 'j', 'fsync'];
|
||||
|
||||
if (writeConcern instanceof WriteConcern) {
|
||||
writeConcern = writeConcern.toJSON();
|
||||
@ -31,10 +31,10 @@ DBCollection.prototype.addIdIfNeeded = function(obj) {
|
||||
throw new Error('argument passed to addIdIfNeeded is not an object');
|
||||
}
|
||||
if (typeof (obj._id) == "undefined" && !Array.isArray(obj)) {
|
||||
var tmp = obj; // don't want to modify input
|
||||
let tmp = obj; // don't want to modify input
|
||||
obj = {_id: new ObjectId()};
|
||||
|
||||
for (var key in tmp) {
|
||||
for (let key in tmp) {
|
||||
if (tmp.hasOwnProperty(key)) {
|
||||
obj[key] = tmp[key];
|
||||
}
|
||||
@ -72,24 +72,24 @@ DBCollection.prototype.addIdIfNeeded = function(obj) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
opts.ordered = (typeof opts.ordered == 'boolean') ? opts.ordered : true;
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulkOp = opts.ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
let bulkOp = opts.ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
|
||||
if (opts.rawData) {
|
||||
bulkOp.setRawData();
|
||||
}
|
||||
|
||||
// Contains all inserted _ids
|
||||
var insertedIds = {};
|
||||
let insertedIds = {};
|
||||
|
||||
// For each of the operations we need to add the op to the bulk
|
||||
operations.forEach(function(op, index) {
|
||||
@ -114,7 +114,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}
|
||||
|
||||
// Translate operation to bulk operation
|
||||
var operation = bulkOp.find(op.updateOne.filter);
|
||||
let operation = bulkOp.find(op.updateOne.filter);
|
||||
if (op.updateOne.sort) {
|
||||
operation.sort(op.updateOne.sort);
|
||||
}
|
||||
@ -151,7 +151,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}
|
||||
|
||||
// Translate operation to bulk operation
|
||||
var operation = bulkOp.find(op.updateMany.filter);
|
||||
let operation = bulkOp.find(op.updateMany.filter);
|
||||
if (op.updateMany.upsert) {
|
||||
operation = operation.upsert();
|
||||
}
|
||||
@ -179,7 +179,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}
|
||||
|
||||
// Translate operation to bulkOp operation
|
||||
var operation = bulkOp.find(op.replaceOne.filter);
|
||||
let operation = bulkOp.find(op.replaceOne.filter);
|
||||
if (op.replaceOne.upsert) {
|
||||
operation = operation.upsert();
|
||||
}
|
||||
@ -199,7 +199,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}
|
||||
|
||||
// Translate operation to bulkOp operation.
|
||||
var deleteOp = bulkOp.find(op.deleteOne.filter);
|
||||
let deleteOp = bulkOp.find(op.deleteOne.filter);
|
||||
|
||||
if (op.deleteOne.collation) {
|
||||
deleteOp.collation(op.deleteOne.collation);
|
||||
@ -212,7 +212,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}
|
||||
|
||||
// Translate operation to bulkOp operation.
|
||||
var deleteOp = bulkOp.find(op.deleteMany.filter);
|
||||
let deleteOp = bulkOp.find(op.deleteMany.filter);
|
||||
|
||||
if (op.deleteMany.collation) {
|
||||
deleteOp.collation(op.deleteMany.collation);
|
||||
@ -223,7 +223,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
}, this);
|
||||
|
||||
// Execute bulkOp operation
|
||||
var response = bulkOp.execute(writeConcern);
|
||||
let response = bulkOp.execute(writeConcern);
|
||||
if (!result.acknowledged) {
|
||||
return result;
|
||||
}
|
||||
@ -236,7 +236,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
result.upsertedIds = {};
|
||||
|
||||
// Iterate over all the upserts
|
||||
var upserts = response.getUpsertedIds();
|
||||
let upserts = response.getUpsertedIds();
|
||||
upserts.forEach(function(x) {
|
||||
result.upsertedIds[x.index] = x._id;
|
||||
});
|
||||
@ -257,19 +257,19 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.insertOne = function(document, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Add _id ObjectId if needed
|
||||
document = this.addIdIfNeeded(document);
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
if (opts.rawData)
|
||||
bulk.setRawData(opts.rawData);
|
||||
@ -317,7 +317,7 @@ DBCollection.prototype.insertOne = function(document, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.insertMany = function(documents, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
opts.ordered = (typeof opts.ordered == 'boolean') ? opts.ordered : true;
|
||||
|
||||
// Ensure all documents have an _id
|
||||
@ -326,13 +326,13 @@ DBCollection.prototype.insertMany = function(documents, options) {
|
||||
}, this);
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = opts.ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
let bulk = opts.ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
|
||||
|
||||
if (opts.rawData)
|
||||
bulk.setRawData(opts.rawData);
|
||||
@ -370,17 +370,17 @@ DBCollection.prototype.insertMany = function(documents, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.deleteOne = function(filter, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
var removeOp = bulk.find(filter);
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
let removeOp = bulk.find(filter);
|
||||
|
||||
// Add the collation, if there is one.
|
||||
if (opts.collation) {
|
||||
@ -394,9 +394,10 @@ DBCollection.prototype.deleteOne = function(filter, options) {
|
||||
// Add the deleteOne operation.
|
||||
removeOp.removeOne();
|
||||
|
||||
let r;
|
||||
try {
|
||||
// Remove the first document that matches the selector
|
||||
var r = bulk.execute(writeConcern);
|
||||
r = bulk.execute(writeConcern);
|
||||
} catch (err) {
|
||||
if (err instanceof BulkWriteError) {
|
||||
if (err.hasWriteErrors()) {
|
||||
@ -431,17 +432,17 @@ DBCollection.prototype.deleteOne = function(filter, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.deleteMany = function(filter, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
var removeOp = bulk.find(filter);
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
let removeOp = bulk.find(filter);
|
||||
|
||||
// Add the collation, if there is one.
|
||||
if (opts.collation) {
|
||||
@ -455,9 +456,10 @@ DBCollection.prototype.deleteMany = function(filter, options) {
|
||||
// Add the deleteOne operation.
|
||||
removeOp.remove();
|
||||
|
||||
let r;
|
||||
try {
|
||||
// Remove all documents that matche the selector
|
||||
var r = bulk.execute(writeConcern);
|
||||
r = bulk.execute(writeConcern);
|
||||
} catch (err) {
|
||||
if (err instanceof BulkWriteError) {
|
||||
if (err.hasWriteErrors()) {
|
||||
@ -494,7 +496,7 @@ DBCollection.prototype.deleteMany = function(filter, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.replaceOne = function(filter, replacement, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Cannot use pipeline-style updates in a replacement operation.
|
||||
if (Array.isArray(replacement)) {
|
||||
@ -502,23 +504,23 @@ DBCollection.prototype.replaceOne = function(filter, replacement, options) {
|
||||
}
|
||||
|
||||
// Check if first key in update statement contains a $
|
||||
var keys = Object.keys(replacement);
|
||||
let keys = Object.keys(replacement);
|
||||
// Check if first key does not have the $
|
||||
if (keys.length > 0 && keys[0][0] == "$") {
|
||||
throw new Error('the replace operation document must not contain atomic operators');
|
||||
}
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
// Add the deleteOne operation
|
||||
var op = bulk.find(filter);
|
||||
let op = bulk.find(filter);
|
||||
if (opts.upsert) {
|
||||
op = op.upsert();
|
||||
}
|
||||
@ -537,9 +539,10 @@ DBCollection.prototype.replaceOne = function(filter, replacement, options) {
|
||||
|
||||
op.replaceOne(replacement);
|
||||
|
||||
let r;
|
||||
try {
|
||||
// Replace the document
|
||||
var r = bulk.execute(writeConcern);
|
||||
r = bulk.execute(writeConcern);
|
||||
} catch (err) {
|
||||
if (err instanceof BulkWriteError) {
|
||||
if (err.hasWriteErrors()) {
|
||||
@ -582,12 +585,12 @@ DBCollection.prototype.replaceOne = function(filter, replacement, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.updateOne = function(filter, update, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Pipeline updates are always permitted. Otherwise, we validate the update object.
|
||||
if (!Array.isArray(update)) {
|
||||
// Check if first key in update statement contains a $
|
||||
var keys = Object.keys(update);
|
||||
let keys = Object.keys(update);
|
||||
if (keys.length == 0) {
|
||||
throw new Error(
|
||||
"the update operation document must contain at least one atomic operator");
|
||||
@ -599,16 +602,16 @@ DBCollection.prototype.updateOne = function(filter, update, options) {
|
||||
}
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
// Add the updateOne operation
|
||||
var op = bulk.find(filter);
|
||||
let op = bulk.find(filter);
|
||||
if (opts.sort) {
|
||||
op.sort(opts.sort);
|
||||
}
|
||||
@ -634,9 +637,10 @@ DBCollection.prototype.updateOne = function(filter, update, options) {
|
||||
|
||||
op.updateOne(update);
|
||||
|
||||
let r;
|
||||
try {
|
||||
// Update the first document that matches the selector
|
||||
var r = bulk.execute(writeConcern);
|
||||
r = bulk.execute(writeConcern);
|
||||
} catch (err) {
|
||||
if (err instanceof BulkWriteError) {
|
||||
if (err.hasWriteErrors()) {
|
||||
@ -679,12 +683,12 @@ DBCollection.prototype.updateOne = function(filter, update, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.updateMany = function(filter, update, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Pipeline updates are always permitted. Otherwise, we validate the update object.
|
||||
if (!Array.isArray(update)) {
|
||||
// Check if first key in update statement contains a $
|
||||
var keys = Object.keys(update);
|
||||
let keys = Object.keys(update);
|
||||
if (keys.length == 0) {
|
||||
throw new Error(
|
||||
"the update operation document must contain at least one atomic operator");
|
||||
@ -696,16 +700,16 @@ DBCollection.prototype.updateMany = function(filter, update, options) {
|
||||
}
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Result
|
||||
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
let result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
|
||||
|
||||
// Use bulk operation API already in the shell
|
||||
var bulk = this.initializeOrderedBulkOp();
|
||||
let bulk = this.initializeOrderedBulkOp();
|
||||
|
||||
// Add the updateMany operation
|
||||
var op = bulk.find(filter);
|
||||
let op = bulk.find(filter);
|
||||
|
||||
if (opts.sort) {
|
||||
throw new Error(
|
||||
@ -734,9 +738,10 @@ DBCollection.prototype.updateMany = function(filter, update, options) {
|
||||
|
||||
op.update(update);
|
||||
|
||||
let r;
|
||||
try {
|
||||
// Update all documents that match the selector
|
||||
var r = bulk.execute(writeConcern);
|
||||
r = bulk.execute(writeConcern);
|
||||
} catch (err) {
|
||||
if (err instanceof BulkWriteError) {
|
||||
if (err.hasWriteErrors()) {
|
||||
@ -779,9 +784,9 @@ DBCollection.prototype.updateMany = function(filter, update, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.findOneAndDelete = function(filter, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
// Set up the command
|
||||
var cmd = {query: filter || {}, remove: true};
|
||||
let cmd = {query: filter || {}, remove: true};
|
||||
|
||||
if (opts.sort) {
|
||||
cmd.sort = opts.sort;
|
||||
@ -804,7 +809,7 @@ DBCollection.prototype.findOneAndDelete = function(filter, options) {
|
||||
}
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Setup the write concern
|
||||
if (writeConcern) {
|
||||
@ -834,7 +839,7 @@ DBCollection.prototype.findOneAndDelete = function(filter, options) {
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.findOneAndReplace = function(filter, replacement, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Cannot use pipeline-style updates in a replacement operation.
|
||||
if (Array.isArray(replacement)) {
|
||||
@ -842,14 +847,14 @@ DBCollection.prototype.findOneAndReplace = function(filter, replacement, options
|
||||
}
|
||||
|
||||
// Check if first key in update statement contains a $
|
||||
var keys = Object.keys(replacement);
|
||||
let keys = Object.keys(replacement);
|
||||
// Check if first key does not have the $
|
||||
if (keys.length > 0 && keys[0][0] == "$") {
|
||||
throw new Error("the replace operation document must not contain atomic operators");
|
||||
}
|
||||
|
||||
// Set up the command
|
||||
var cmd = {query: filter || {}, update: replacement};
|
||||
let cmd = {query: filter || {}, update: replacement};
|
||||
if (opts.sort) {
|
||||
cmd.sort = opts.sort;
|
||||
}
|
||||
@ -879,7 +884,7 @@ DBCollection.prototype.findOneAndReplace = function(filter, replacement, options
|
||||
cmd.new = (typeof opts.returnNewDocument == 'boolean') ? opts.returnNewDocument : false;
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Setup the write concern
|
||||
if (writeConcern) {
|
||||
@ -909,12 +914,12 @@ DBCollection.prototype.findOneAndReplace = function(filter, replacement, options
|
||||
* @return {object}
|
||||
*/
|
||||
DBCollection.prototype.findOneAndUpdate = function(filter, update, options) {
|
||||
var opts = Object.extend({}, options || {});
|
||||
let opts = Object.extend({}, options || {});
|
||||
|
||||
// Pipeline updates are always permitted. Otherwise, we validate the update object.
|
||||
if (!Array.isArray(update)) {
|
||||
// Check if first key in update statement contains a $
|
||||
var keys = Object.keys(update);
|
||||
let keys = Object.keys(update);
|
||||
if (keys.length == 0) {
|
||||
throw new Error(
|
||||
"the update operation document must contain at least one atomic operator");
|
||||
@ -926,7 +931,7 @@ DBCollection.prototype.findOneAndUpdate = function(filter, update, options) {
|
||||
}
|
||||
|
||||
// Set up the command
|
||||
var cmd = {query: filter || {}, update: update};
|
||||
let cmd = {query: filter || {}, update: update};
|
||||
if (opts.sort) {
|
||||
cmd.sort = opts.sort;
|
||||
}
|
||||
@ -960,7 +965,7 @@ DBCollection.prototype.findOneAndUpdate = function(filter, update, options) {
|
||||
cmd.new = (typeof opts.returnNewDocument == 'boolean') ? opts.returnNewDocument : false;
|
||||
|
||||
// Get the write concern
|
||||
var writeConcern = this._createWriteConcern(opts);
|
||||
let writeConcern = this._createWriteConcern(opts);
|
||||
|
||||
// Setup the write concern
|
||||
if (writeConcern) {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
// db.js
|
||||
|
||||
var _defaultWriteConcern = {w: 'majority', wtimeout: 10 * 60 * 1000};
|
||||
let _defaultWriteConcern = {w: 'majority', wtimeout: 10 * 60 * 1000};
|
||||
const kWireVersionSupportingScramSha256Fallback = 15;
|
||||
|
||||
const DB = globalThis.DB ?? function(mongo, name) {
|
||||
@ -36,7 +36,7 @@ DB.prototype.getName = function() {
|
||||
* or a document with options passed along to the dbstats command.
|
||||
*/
|
||||
DB.prototype.stats = function(opt) {
|
||||
var cmd = {dbstats: 1};
|
||||
let cmd = {dbstats: 1};
|
||||
|
||||
if (opt === undefined)
|
||||
return this.runCommand(cmd);
|
||||
@ -51,10 +51,10 @@ DB.prototype.getCollection = function(name) {
|
||||
};
|
||||
|
||||
DB.prototype.commandHelp = function(name) {
|
||||
var c = {};
|
||||
let c = {};
|
||||
c[name] = 1;
|
||||
c.help = true;
|
||||
var res = this.runCommand(c);
|
||||
let res = this.runCommand(c);
|
||||
if (!res.ok)
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
return res.help;
|
||||
@ -91,7 +91,7 @@ DB.prototype._attachReadPreferenceToCommand = function(cmdObj, readPref) {
|
||||
}
|
||||
|
||||
// Copy object so we don't mutate the original.
|
||||
var clonedCmdObj = Object.extend({}, cmdObj);
|
||||
let clonedCmdObj = Object.extend({}, cmdObj);
|
||||
clonedCmdObj["$readPreference"] = readPref;
|
||||
return clonedCmdObj;
|
||||
};
|
||||
@ -119,8 +119,8 @@ DB.prototype._mergeCommandOptions = function(obj, extraKeys) {
|
||||
"(type: " + typeof (obj) + "): " + tojson(obj));
|
||||
}
|
||||
|
||||
var commandName = obj;
|
||||
var mergedCmdObj = {};
|
||||
let commandName = obj;
|
||||
let mergedCmdObj = {};
|
||||
mergedCmdObj[commandName] = 1;
|
||||
|
||||
if (!extraKeys) {
|
||||
@ -128,7 +128,7 @@ DB.prototype._mergeCommandOptions = function(obj, extraKeys) {
|
||||
} else if (typeof (extraKeys) === "object") {
|
||||
// this will traverse the prototype chain of extra, but keeping
|
||||
// to maintain legacy behavior
|
||||
for (var key in extraKeys) {
|
||||
for (let key in extraKeys) {
|
||||
mergedCmdObj[key] = extraKeys[key];
|
||||
}
|
||||
} else {
|
||||
@ -180,11 +180,11 @@ DB.prototype.runCommand = function(obj, extra, queryOptions) {
|
||||
|
||||
// Support users who call this function with a string commandName, e.g.
|
||||
// db.runCommand("commandName", {arg1: "value", arg2: "value"}).
|
||||
var mergedObj = this._mergeCommandOptions(obj, extra);
|
||||
let mergedObj = this._mergeCommandOptions(obj, extra);
|
||||
|
||||
// if options were passed (i.e. because they were overridden on a collection), use them.
|
||||
// Otherwise use getQueryOptions.
|
||||
var options = (typeof (queryOptions) !== "undefined") ? queryOptions : this.getQueryOptions();
|
||||
let options = (typeof (queryOptions) !== "undefined") ? queryOptions : this.getQueryOptions();
|
||||
|
||||
try {
|
||||
return this._runCommandImpl(this._name, mergedObj, options);
|
||||
@ -338,9 +338,9 @@ DB.prototype.aggregate = function(pipeline, aggregateOptions) {
|
||||
* @return {Object} returned has member ok set to true if operation succeeds, false otherwise.
|
||||
*/
|
||||
DB.prototype.createCollection = function(name, opt) {
|
||||
var options = opt || {};
|
||||
let options = opt || {};
|
||||
|
||||
var cmd = {create: name};
|
||||
let cmd = {create: name};
|
||||
Object.extend(cmd, options);
|
||||
|
||||
return this._dbCommand(cmd);
|
||||
@ -356,9 +356,9 @@ DB.prototype.createCollection = function(name, opt) {
|
||||
* @param options { } - options on the view, e.g., collations
|
||||
*/
|
||||
DB.prototype.createView = function(name, viewOn, pipeline, opt) {
|
||||
var options = opt || {};
|
||||
let options = opt || {};
|
||||
|
||||
var cmd = {create: name};
|
||||
let cmd = {create: name};
|
||||
|
||||
if (viewOn == undefined) {
|
||||
throw Error("Must specify a backing view or collection");
|
||||
@ -385,7 +385,7 @@ DB.prototype.createView = function(name, viewOn, pipeline, opt) {
|
||||
* @return SOMETHING_FIXME or null on error
|
||||
*/
|
||||
DB.prototype.getProfilingLevel = function() {
|
||||
var res = assert.commandWorked(this._dbCommand({profile: -1}));
|
||||
let res = assert.commandWorked(this._dbCommand({profile: -1}));
|
||||
return res ? res.was : null;
|
||||
};
|
||||
|
||||
@ -395,7 +395,7 @@ DB.prototype.getProfilingLevel = function() {
|
||||
* @return SOMETHING_FIXME or null on error
|
||||
*/
|
||||
DB.prototype.getProfilingStatus = function() {
|
||||
var res = this._dbCommand({profile: -1});
|
||||
let res = this._dbCommand({profile: -1});
|
||||
if (!res.ok)
|
||||
throw _getErrorWithCode(res, "profile command failed: " + tojson(res));
|
||||
delete res.ok;
|
||||
@ -425,14 +425,14 @@ DB.prototype.shutdownServer = function(opts) {
|
||||
return "shutdown command only works with the admin database; try 'use admin'";
|
||||
}
|
||||
|
||||
var cmd = {'shutdown': 1};
|
||||
let cmd = {'shutdown': 1};
|
||||
opts = opts || {};
|
||||
for (var o in opts) {
|
||||
for (let o in opts) {
|
||||
cmd[o] = opts[o];
|
||||
}
|
||||
|
||||
try {
|
||||
var res = this.runCommand(cmd);
|
||||
let res = this.runCommand(cmd);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, 'shutdownServer failed: ' + tojson(res));
|
||||
}
|
||||
@ -525,7 +525,7 @@ DB.prototype.printCollectionStats = function(scale) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
var mydb = this;
|
||||
let mydb = this;
|
||||
this.getCollectionNames().forEach(function(z) {
|
||||
print(z);
|
||||
printjson(mydb.getCollection(z).stats(scale));
|
||||
@ -554,13 +554,13 @@ DB.prototype.printCollectionStats = function(scale) {
|
||||
*/
|
||||
DB.prototype.setProfilingLevel = function(level, options) {
|
||||
if (level < 0 || level > 2) {
|
||||
var errorText = "input level " + level + " is out of range [0..2]";
|
||||
var errorObject = new Error(errorText);
|
||||
let errorText = "input level " + level + " is out of range [0..2]";
|
||||
let errorObject = new Error(errorText);
|
||||
errorObject['dbSetProfilingException'] = errorText;
|
||||
throw errorObject;
|
||||
}
|
||||
|
||||
var cmd = {profile: level};
|
||||
let cmd = {profile: level};
|
||||
if (isNumber(options)) {
|
||||
cmd.slowms = options;
|
||||
} else {
|
||||
@ -596,12 +596,12 @@ DB.prototype.setProfilingLevel = function(level, options) {
|
||||
DB.prototype.eval = function(jsfunction) {
|
||||
print("WARNING: db.eval is deprecated");
|
||||
|
||||
var cmd = {$eval: jsfunction};
|
||||
let cmd = {$eval: jsfunction};
|
||||
if (arguments.length > 1) {
|
||||
cmd.args = Array.from(arguments).slice(1);
|
||||
}
|
||||
|
||||
var res = this._dbCommand(cmd);
|
||||
let res = this._dbCommand(cmd);
|
||||
|
||||
if (!res.ok)
|
||||
throw _getErrorWithCode(res, tojson(res));
|
||||
@ -626,28 +626,28 @@ DB.prototype.dbEval = DB.prototype.eval;
|
||||
* </p>
|
||||
*/
|
||||
DB.prototype.groupeval = function(parmsObj) {
|
||||
var groupFunction = function() {
|
||||
let groupFunction = function() {
|
||||
var parms = args[0]; // eslint-disable-line
|
||||
var c = globalThis.db[parms.ns].find(parms.cond || {});
|
||||
var map = new BSONAwareMap();
|
||||
var pks = parms.key ? Object.keySet(parms.key) : null;
|
||||
var pkl = pks ? pks.length : 0;
|
||||
var key = {};
|
||||
let c = globalThis.db[parms.ns].find(parms.cond || {});
|
||||
let map = new BSONAwareMap();
|
||||
let pks = parms.key ? Object.keySet(parms.key) : null;
|
||||
let pkl = pks ? pks.length : 0;
|
||||
let key = {};
|
||||
|
||||
while (c.hasNext()) {
|
||||
var obj = c.next();
|
||||
let obj = c.next();
|
||||
if (pks) {
|
||||
for (var i = 0; i < pkl; i++) {
|
||||
var k = pks[i];
|
||||
for (let i = 0; i < pkl; i++) {
|
||||
let k = pks[i];
|
||||
key[k] = obj[k];
|
||||
}
|
||||
} else {
|
||||
key = parms.$keyf(obj);
|
||||
}
|
||||
|
||||
var aggObj = map.get(key);
|
||||
let aggObj = map.get(key);
|
||||
if (aggObj == null) {
|
||||
var newObj = Object.extend({}, key); // clone
|
||||
let newObj = Object.extend({}, key); // clone
|
||||
aggObj = Object.extend(newObj, parms.initial);
|
||||
map.put(key, aggObj);
|
||||
}
|
||||
@ -661,7 +661,7 @@ DB.prototype.groupeval = function(parmsObj) {
|
||||
};
|
||||
|
||||
DB.prototype._groupFixParms = function(parmsObj) {
|
||||
var parms = Object.extend({}, parmsObj);
|
||||
let parms = Object.extend({}, parmsObj);
|
||||
|
||||
if (parms.reduce) {
|
||||
parms.$reduce = parms.reduce; // must have $ to pass to db
|
||||
@ -873,11 +873,11 @@ DB.tsToSeconds = function(x) {
|
||||
* of date than that, it can't recover without a complete resync
|
||||
*/
|
||||
DB.prototype.getReplicationInfo = function() {
|
||||
var localdb = this.getSiblingDB("local");
|
||||
let localdb = this.getSiblingDB("local");
|
||||
|
||||
var result = {};
|
||||
var oplog;
|
||||
var localCollections = localdb.getCollectionNames();
|
||||
let result = {};
|
||||
let oplog;
|
||||
let localCollections = localdb.getCollectionNames();
|
||||
if (localCollections.indexOf('oplog.rs') >= 0) {
|
||||
oplog = 'oplog.rs';
|
||||
} else {
|
||||
@ -885,8 +885,8 @@ DB.prototype.getReplicationInfo = function() {
|
||||
return result;
|
||||
}
|
||||
|
||||
var ol = localdb.getCollection(oplog);
|
||||
var ol_stats = ol.stats();
|
||||
let ol = localdb.getCollection(oplog);
|
||||
let ol_stats = ol.stats();
|
||||
if (ol_stats && ol_stats.maxSize) {
|
||||
result.logSizeMB = ol_stats.maxSize / (1024 * 1024);
|
||||
} else {
|
||||
@ -898,8 +898,8 @@ DB.prototype.getReplicationInfo = function() {
|
||||
result.usedMB = ol_stats.size / (1024 * 1024);
|
||||
result.usedMB = Math.ceil(result.usedMB * 100) / 100;
|
||||
|
||||
var firstc = ol.find().sort({$natural: 1}).limit(1);
|
||||
var lastc = ol.find().sort({$natural: -1}).limit(1);
|
||||
let firstc = ol.find().sort({$natural: 1}).limit(1);
|
||||
let lastc = ol.find().sort({$natural: -1}).limit(1);
|
||||
if (!firstc.hasNext() || !lastc.hasNext()) {
|
||||
result.errmsg =
|
||||
"objects not found in local.oplog.$main -- is this a new and empty db instance?";
|
||||
@ -907,10 +907,10 @@ DB.prototype.getReplicationInfo = function() {
|
||||
return result;
|
||||
}
|
||||
|
||||
var first = firstc.next();
|
||||
var last = lastc.next();
|
||||
var tfirst = first.ts;
|
||||
var tlast = last.ts;
|
||||
let first = firstc.next();
|
||||
let last = lastc.next();
|
||||
let tfirst = first.ts;
|
||||
let tlast = last.ts;
|
||||
|
||||
if (tfirst && tlast) {
|
||||
tfirst = DB.tsToSeconds(tfirst);
|
||||
@ -928,7 +928,7 @@ DB.prototype.getReplicationInfo = function() {
|
||||
};
|
||||
|
||||
DB.prototype.printReplicationInfo = function() {
|
||||
var result = this.getReplicationInfo();
|
||||
let result = this.getReplicationInfo();
|
||||
if (result.errmsg) {
|
||||
let reply, isPrimary;
|
||||
if (this.getMongo().getApiParameters().apiVersion) {
|
||||
@ -964,15 +964,15 @@ DB.prototype.printSlaveReplicationInfo = function() {
|
||||
};
|
||||
|
||||
DB.prototype.printSecondaryReplicationInfo = function() {
|
||||
var startOptimeDate = null;
|
||||
var primary = null;
|
||||
let startOptimeDate = null;
|
||||
let primary = null;
|
||||
|
||||
function getReplLag(st) {
|
||||
assert(startOptimeDate, "how could this be null (getReplLag startOptimeDate)");
|
||||
print("\tsyncedTo: " + st.toString());
|
||||
var ago = (startOptimeDate - st) / 1000;
|
||||
var hrs = Math.round(ago / 36) / 100;
|
||||
var suffix = "";
|
||||
let ago = (startOptimeDate - st) / 1000;
|
||||
let hrs = Math.round(ago / 36) / 100;
|
||||
let suffix = "";
|
||||
if (primary) {
|
||||
suffix = "primary ";
|
||||
} else {
|
||||
@ -983,7 +983,7 @@ DB.prototype.printSecondaryReplicationInfo = function() {
|
||||
|
||||
function getPrimary(members) {
|
||||
for (let i in members) {
|
||||
var row = members[i];
|
||||
let row = members[i];
|
||||
if (row.state === 1) {
|
||||
return row;
|
||||
}
|
||||
@ -1014,7 +1014,7 @@ DB.prototype.printSecondaryReplicationInfo = function() {
|
||||
" minute(s)");
|
||||
}
|
||||
|
||||
var L = this.getSiblingDB("local");
|
||||
let L = this.getSiblingDB("local");
|
||||
|
||||
if (L.system.replset.count() != 0) {
|
||||
const status =
|
||||
@ -1059,7 +1059,7 @@ DB.prototype.serverBuildInfo = function() {
|
||||
};
|
||||
|
||||
DB.prototype.serverStatus = function(options) {
|
||||
var cmd = {serverStatus: 1};
|
||||
let cmd = {serverStatus: 1};
|
||||
if (options) {
|
||||
Object.extend(cmd, options);
|
||||
}
|
||||
@ -1086,11 +1086,11 @@ DB.prototype.serverBits = function() {
|
||||
};
|
||||
|
||||
DB.prototype.listCommands = function() {
|
||||
var x = this.runCommand("listCommands");
|
||||
for (var name in x.commands) {
|
||||
var c = x.commands[name];
|
||||
let x = this.runCommand("listCommands");
|
||||
for (let name in x.commands) {
|
||||
let c = x.commands[name];
|
||||
|
||||
var s = name + ": ";
|
||||
let s = name + ": ";
|
||||
|
||||
if (c.adminOnly)
|
||||
s += " adminOnly ";
|
||||
@ -1121,9 +1121,9 @@ DB.autocomplete = function(obj) {
|
||||
// In interactive mode, time out if a transaction or other op holds locks we need. Caller
|
||||
// suppresses exceptions. In non-interactive mode, don't specify a timeout, because in an
|
||||
// automated test we prefer consistent results over quick feedback.
|
||||
var colls = obj._getCollectionNamesInternal(isInteractive() ? {maxTimeMS: 1000} : {});
|
||||
var ret = [];
|
||||
for (var i = 0; i < colls.length; i++) {
|
||||
let colls = obj._getCollectionNamesInternal(isInteractive() ? {maxTimeMS: 1000} : {});
|
||||
let ret = [];
|
||||
for (let i = 0; i < colls.length; i++) {
|
||||
if (colls[i].match(/^[a-zA-Z0-9_.\$]+$/))
|
||||
ret.push(colls[i]);
|
||||
}
|
||||
@ -1153,7 +1153,7 @@ DB.prototype.getSecondaryOk = function() {
|
||||
};
|
||||
|
||||
DB.prototype.getQueryOptions = function() {
|
||||
var options = 0;
|
||||
let options = 0;
|
||||
if (this.getSecondaryOk())
|
||||
options |= 4;
|
||||
return options;
|
||||
@ -1162,7 +1162,7 @@ DB.prototype.getQueryOptions = function() {
|
||||
/* Loads any scripts contained in system.js into the client shell.
|
||||
*/
|
||||
DB.prototype.loadServerScripts = function() {
|
||||
var global = Function('return this')();
|
||||
let global = Function('return this')();
|
||||
this.getCollection('system.js').find().forEach(function(u) {
|
||||
if (u.value.constructor === Code) {
|
||||
global[u._id] = eval("(" + u.value.code + ")");
|
||||
@ -1178,9 +1178,9 @@ DB.prototype.loadServerScripts = function() {
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
function getUserObjString(userObj) {
|
||||
var pwd = userObj.pwd;
|
||||
let pwd = userObj.pwd;
|
||||
delete userObj.pwd;
|
||||
var toreturn = tojson(userObj);
|
||||
let toreturn = tojson(userObj);
|
||||
userObj.pwd = pwd;
|
||||
return toreturn;
|
||||
}
|
||||
@ -1193,7 +1193,7 @@ DB.prototype._modifyCommandToDigestPasswordIfNecessary = function(cmdObj, userna
|
||||
throw Error("Cannot specify 'digestPassword' through the user management shell helpers, " +
|
||||
"use 'passwordDigestor' instead");
|
||||
}
|
||||
var passwordDigestor = cmdObj["passwordDigestor"] ? cmdObj["passwordDigestor"] : "server";
|
||||
let passwordDigestor = cmdObj["passwordDigestor"] ? cmdObj["passwordDigestor"] : "server";
|
||||
if (passwordDigestor == "server") {
|
||||
cmdObj["digestPassword"] = true;
|
||||
} else if (passwordDigestor == "client") {
|
||||
@ -1207,7 +1207,7 @@ DB.prototype._modifyCommandToDigestPasswordIfNecessary = function(cmdObj, userna
|
||||
};
|
||||
|
||||
DB.prototype.createUser = function(userObj, writeConcern) {
|
||||
var name = userObj["user"];
|
||||
let name = userObj["user"];
|
||||
if (name === undefined) {
|
||||
throw Error("no 'user' field provided to 'createUser' function");
|
||||
}
|
||||
@ -1216,7 +1216,7 @@ DB.prototype.createUser = function(userObj, writeConcern) {
|
||||
throw Error("calling 'createUser' function with 'createUser' field is disallowed");
|
||||
}
|
||||
|
||||
var cmdObj = {createUser: name};
|
||||
let cmdObj = {createUser: name};
|
||||
cmdObj = Object.extend(cmdObj, userObj);
|
||||
delete cmdObj["user"];
|
||||
|
||||
@ -1224,7 +1224,7 @@ DB.prototype.createUser = function(userObj, writeConcern) {
|
||||
|
||||
cmdObj["writeConcern"] = writeConcern ? writeConcern : _defaultWriteConcern;
|
||||
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
|
||||
if (res.ok) {
|
||||
print("Successfully added user: " + getUserObjString(userObj));
|
||||
@ -1253,12 +1253,12 @@ function _hashPassword(username, password) {
|
||||
}
|
||||
|
||||
DB.prototype.updateUser = function(name, updateObject, writeConcern) {
|
||||
var cmdObj = {updateUser: name};
|
||||
let cmdObj = {updateUser: name};
|
||||
cmdObj = Object.extend(cmdObj, updateObject);
|
||||
cmdObj['writeConcern'] = writeConcern ? writeConcern : _defaultWriteConcern;
|
||||
this._modifyCommandToDigestPasswordIfNecessary(cmdObj, name);
|
||||
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (res.ok) {
|
||||
return;
|
||||
}
|
||||
@ -1282,11 +1282,11 @@ DB.prototype.removeUser = function(username, writeConcern) {
|
||||
};
|
||||
|
||||
DB.prototype.dropUser = function(username, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
dropUser: username,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
|
||||
if (res.ok) {
|
||||
return true;
|
||||
@ -1300,7 +1300,7 @@ DB.prototype.dropUser = function(username, writeConcern) {
|
||||
};
|
||||
|
||||
DB.prototype.dropAllUsers = function(writeConcern) {
|
||||
var res = this.runCommand({
|
||||
let res = this.runCommand({
|
||||
dropAllUsersFromDatabase: 1,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
});
|
||||
@ -1342,7 +1342,7 @@ DB.prototype._getDefaultAuthenticationMechanism = function(username, database) {
|
||||
|
||||
// Never include PLAIN in auto-negotiation.
|
||||
const priority = ["GSSAPI", "SCRAM-SHA-256", "SCRAM-SHA-1"];
|
||||
for (var i = 0; i < priority.length; ++i) {
|
||||
for (let i = 0; i < priority.length; ++i) {
|
||||
if (mechs.includes(priority[i])) {
|
||||
return priority[i];
|
||||
}
|
||||
@ -1367,7 +1367,7 @@ DB.prototype._getDefaultAuthenticationMechanism = function(username, database) {
|
||||
DB.prototype._defaultGssapiServiceName = null;
|
||||
|
||||
DB.prototype._authOrThrow = function() {
|
||||
var params;
|
||||
let params;
|
||||
if (arguments.length == 2) {
|
||||
params = {user: arguments[0], pwd: arguments[1]};
|
||||
} else if (arguments.length == 1) {
|
||||
@ -1399,7 +1399,7 @@ DB.prototype._authOrThrow = function() {
|
||||
|
||||
// Logging in doesn't require a session since it manipulates connection state.
|
||||
params.db = this.getName();
|
||||
var good = this.getMongo().auth(params);
|
||||
let good = this.getMongo().auth(params);
|
||||
if (good) {
|
||||
// auth enabled, and should try to use hello and replSetGetStatus to build prompt
|
||||
this.getMongo().authStatus = {authRequired: true, hello: true, replSetGetStatus: true};
|
||||
@ -1409,7 +1409,7 @@ DB.prototype._authOrThrow = function() {
|
||||
};
|
||||
|
||||
DB.prototype.auth = function() {
|
||||
var ex;
|
||||
let ex;
|
||||
try {
|
||||
this._authOrThrow.apply(this, arguments);
|
||||
} catch (ex) {
|
||||
@ -1420,24 +1420,24 @@ DB.prototype.auth = function() {
|
||||
};
|
||||
|
||||
DB.prototype.grantRolesToUser = function(username, roles, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
grantRolesToUser: username,
|
||||
roles: roles,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
};
|
||||
|
||||
DB.prototype.revokeRolesFromUser = function(username, roles, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
revokeRolesFromUser: username,
|
||||
roles: roles,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
@ -1447,10 +1447,10 @@ DB.prototype.getUser = function(username, args) {
|
||||
if (typeof username != "string") {
|
||||
throw Error("User name for getUser shell helper must be a string");
|
||||
}
|
||||
var cmdObj = {usersInfo: username};
|
||||
let cmdObj = {usersInfo: username};
|
||||
Object.extend(cmdObj, args);
|
||||
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
@ -1462,11 +1462,11 @@ DB.prototype.getUser = function(username, args) {
|
||||
};
|
||||
|
||||
DB.prototype.getUsers = function(args) {
|
||||
var cmdObj = {usersInfo: 1};
|
||||
let cmdObj = {usersInfo: 1};
|
||||
Object.extend(cmdObj, args);
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
var authSchemaIncompatibleCode = 69;
|
||||
let authSchemaIncompatibleCode = 69;
|
||||
if (res.code == authSchemaIncompatibleCode ||
|
||||
(res.code == null && res.errmsg == "no such cmd: usersInfo")) {
|
||||
// Working with 2.4 schema user data
|
||||
@ -1480,13 +1480,13 @@ DB.prototype.getUsers = function(args) {
|
||||
};
|
||||
|
||||
DB.prototype.createRole = function(roleObj, writeConcern) {
|
||||
var name = roleObj["role"];
|
||||
var cmdObj = {createRole: name};
|
||||
let name = roleObj["role"];
|
||||
let cmdObj = {createRole: name};
|
||||
cmdObj = Object.extend(cmdObj, roleObj);
|
||||
delete cmdObj["role"];
|
||||
cmdObj["writeConcern"] = writeConcern ? writeConcern : _defaultWriteConcern;
|
||||
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
@ -1495,18 +1495,18 @@ DB.prototype.createRole = function(roleObj, writeConcern) {
|
||||
};
|
||||
|
||||
DB.prototype.updateRole = function(name, updateObject, writeConcern) {
|
||||
var cmdObj = {updateRole: name};
|
||||
let cmdObj = {updateRole: name};
|
||||
cmdObj = Object.extend(cmdObj, updateObject);
|
||||
cmdObj['writeConcern'] = writeConcern ? writeConcern : _defaultWriteConcern;
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
};
|
||||
|
||||
DB.prototype.dropRole = function(name, writeConcern) {
|
||||
var cmdObj = {dropRole: name, writeConcern: writeConcern ? writeConcern : _defaultWriteConcern};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let cmdObj = {dropRole: name, writeConcern: writeConcern ? writeConcern : _defaultWriteConcern};
|
||||
let res = this.runCommand(cmdObj);
|
||||
|
||||
if (res.ok) {
|
||||
return true;
|
||||
@ -1520,7 +1520,7 @@ DB.prototype.dropRole = function(name, writeConcern) {
|
||||
};
|
||||
|
||||
DB.prototype.dropAllRoles = function(writeConcern) {
|
||||
var res = this.runCommand({
|
||||
let res = this.runCommand({
|
||||
dropAllRolesFromDatabase: 1,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
});
|
||||
@ -1533,48 +1533,48 @@ DB.prototype.dropAllRoles = function(writeConcern) {
|
||||
};
|
||||
|
||||
DB.prototype.grantRolesToRole = function(rolename, roles, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
grantRolesToRole: rolename,
|
||||
roles: roles,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
};
|
||||
|
||||
DB.prototype.revokeRolesFromRole = function(rolename, roles, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
revokeRolesFromRole: rolename,
|
||||
roles: roles,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
};
|
||||
|
||||
DB.prototype.grantPrivilegesToRole = function(rolename, privileges, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
grantPrivilegesToRole: rolename,
|
||||
privileges: privileges,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
};
|
||||
|
||||
DB.prototype.revokePrivilegesFromRole = function(rolename, privileges, writeConcern) {
|
||||
var cmdObj = {
|
||||
let cmdObj = {
|
||||
revokePrivilegesFromRole: rolename,
|
||||
privileges: privileges,
|
||||
writeConcern: writeConcern ? writeConcern : _defaultWriteConcern
|
||||
};
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
@ -1584,9 +1584,9 @@ DB.prototype.getRole = function(rolename, args) {
|
||||
if (typeof rolename != "string") {
|
||||
throw Error("Role name for getRole shell helper must be a string");
|
||||
}
|
||||
var cmdObj = {rolesInfo: rolename};
|
||||
let cmdObj = {rolesInfo: rolename};
|
||||
Object.extend(cmdObj, args);
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
@ -1598,9 +1598,9 @@ DB.prototype.getRole = function(rolename, args) {
|
||||
};
|
||||
|
||||
DB.prototype.getRoles = function(args) {
|
||||
var cmdObj = {rolesInfo: 1};
|
||||
let cmdObj = {rolesInfo: 1};
|
||||
Object.extend(cmdObj, args);
|
||||
var res = this.runCommand(cmdObj);
|
||||
let res = this.runCommand(cmdObj);
|
||||
if (!res.ok) {
|
||||
throw _getErrorWithCode(res, res.errmsg);
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ class DBExplainQuery {
|
||||
// DBQuery.
|
||||
//
|
||||
|
||||
var delegationFuncNames = [
|
||||
let delegationFuncNames = [
|
||||
"addOption",
|
||||
"allowDiskUse",
|
||||
"batchSize",
|
||||
@ -86,7 +86,7 @@ class DBExplainQuery {
|
||||
|
||||
// Convert this explain query into an explain command, and send the command to
|
||||
// the server.
|
||||
var innerCmd;
|
||||
let innerCmd;
|
||||
if (this._isCount) {
|
||||
// True means to always apply the skip and limit values.
|
||||
innerCmd = this._query._convertToCountCmd(this._applySkipLimit);
|
||||
@ -94,7 +94,7 @@ class DBExplainQuery {
|
||||
innerCmd = this._query._convertToCommand();
|
||||
}
|
||||
|
||||
var explainCmd = {explain: innerCmd};
|
||||
let explainCmd = {explain: innerCmd};
|
||||
explainCmd["verbosity"] = this._verbosity;
|
||||
|
||||
// If "maxTimeMS" or "$readPreference" are set on 'innerCmd', they need to be
|
||||
@ -106,8 +106,8 @@ class DBExplainQuery {
|
||||
explainCmd["$readPreference"] = innerCmd["$readPreference"];
|
||||
}
|
||||
|
||||
var explainDb = this._query._db;
|
||||
var explainResult = explainDb.runReadCommand(explainCmd, null, this._query._options);
|
||||
let explainDb = this._query._db;
|
||||
let explainResult = explainDb.runReadCommand(explainCmd, null, this._query._options);
|
||||
|
||||
return Explainable.throwOrReturn(explainResult);
|
||||
};
|
||||
@ -145,7 +145,7 @@ class DBExplainQuery {
|
||||
* print the result of running the explain.
|
||||
*/
|
||||
shellPrint() {
|
||||
var result = this.finish();
|
||||
let result = this.finish();
|
||||
return tojson(result);
|
||||
};
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// normally.
|
||||
//
|
||||
|
||||
var parseVerbosity = function(verbosity) {
|
||||
let parseVerbosity = function(verbosity) {
|
||||
// Truthy non-strings are interpreted as "allPlansExecution" verbosity.
|
||||
if (verbosity && (typeof verbosity !== "string")) {
|
||||
return "allPlansExecution";
|
||||
@ -19,7 +19,7 @@ var parseVerbosity = function(verbosity) {
|
||||
return verbosity;
|
||||
};
|
||||
|
||||
var throwOrReturn = function(explainResult) {
|
||||
let throwOrReturn = function(explainResult) {
|
||||
if (("ok" in explainResult && !explainResult.ok) || explainResult.$err) {
|
||||
throw _getErrorWithCode(explainResult, "explain failed: " + tojson(explainResult));
|
||||
}
|
||||
@ -27,8 +27,8 @@ var throwOrReturn = function(explainResult) {
|
||||
return explainResult;
|
||||
};
|
||||
|
||||
var buildExplainCmd = function(innerCmd, verbosity) {
|
||||
var explainCmd = {"explain": innerCmd, "verbosity": verbosity};
|
||||
let buildExplainCmd = function(innerCmd, verbosity) {
|
||||
let explainCmd = {"explain": innerCmd, "verbosity": verbosity};
|
||||
// If "maxTimeMS" is set on innerCmd, it needs to be propagated to the top-level
|
||||
// of explainCmd so that it has the intended effect.
|
||||
if (innerCmd.hasOwnProperty("maxTimeMS")) {
|
||||
@ -136,19 +136,19 @@ function Explainable(collection, verbosity) {
|
||||
* to the server.
|
||||
*/
|
||||
this.find = function() {
|
||||
var cursor = this._collection.find.apply(this._collection, arguments);
|
||||
let cursor = this._collection.find.apply(this._collection, arguments);
|
||||
return new DBExplainQuery(cursor, this._verbosity);
|
||||
};
|
||||
|
||||
this.findAndModify = function(params) {
|
||||
var famCmd = Object.extend({"findAndModify": this._collection.getName()}, params);
|
||||
var explainCmd = buildExplainCmd(famCmd, this._verbosity);
|
||||
var explainResult = this._collection.runReadCommand(explainCmd);
|
||||
let famCmd = Object.extend({"findAndModify": this._collection.getName()}, params);
|
||||
let explainCmd = buildExplainCmd(famCmd, this._verbosity);
|
||||
let explainResult = this._collection.runReadCommand(explainCmd);
|
||||
return throwOrReturn(explainResult);
|
||||
};
|
||||
|
||||
this.distinct = function(keyString, query, options) {
|
||||
var distinctCmd = {
|
||||
let distinctCmd = {
|
||||
distinct: this._collection.getName(),
|
||||
key: keyString,
|
||||
query: query || {}
|
||||
@ -167,25 +167,25 @@ function Explainable(collection, verbosity) {
|
||||
distinctCmd.rawData = options.rawData;
|
||||
}
|
||||
|
||||
var explainCmd = buildExplainCmd(distinctCmd, this._verbosity);
|
||||
var explainResult = this._collection.runReadCommand(explainCmd);
|
||||
let explainCmd = buildExplainCmd(distinctCmd, this._verbosity);
|
||||
let explainResult = this._collection.runReadCommand(explainCmd);
|
||||
return throwOrReturn(explainResult);
|
||||
};
|
||||
|
||||
this.remove = function() {
|
||||
var parsed = this._collection._parseRemove.apply(this._collection, arguments);
|
||||
var query = parsed.query;
|
||||
var justOne = parsed.justOne;
|
||||
var collation = parsed.collation;
|
||||
var rawData = parsed.rawData;
|
||||
let parsed = this._collection._parseRemove.apply(this._collection, arguments);
|
||||
let query = parsed.query;
|
||||
let justOne = parsed.justOne;
|
||||
let collation = parsed.collation;
|
||||
let rawData = parsed.rawData;
|
||||
|
||||
var bulk = this._collection.initializeOrderedBulkOp();
|
||||
let bulk = this._collection.initializeOrderedBulkOp();
|
||||
|
||||
if (rawData) {
|
||||
bulk.setRawData(rawData);
|
||||
}
|
||||
|
||||
var removeOp = bulk.find(query);
|
||||
let removeOp = bulk.find(query);
|
||||
|
||||
if (collation) {
|
||||
removeOp.collation(collation);
|
||||
@ -197,29 +197,29 @@ function Explainable(collection, verbosity) {
|
||||
removeOp.remove();
|
||||
}
|
||||
|
||||
var explainCmd = bulk.convertToExplainCmd(this._verbosity);
|
||||
var explainResult = this._collection.runCommand(explainCmd);
|
||||
let explainCmd = bulk.convertToExplainCmd(this._verbosity);
|
||||
let explainResult = this._collection.runCommand(explainCmd);
|
||||
return throwOrReturn(explainResult);
|
||||
};
|
||||
|
||||
this.update = function() {
|
||||
var parsed = this._collection._parseUpdate.apply(this._collection, arguments);
|
||||
var query = parsed.query;
|
||||
var updateSpec = parsed.updateSpec;
|
||||
var upsert = parsed.upsert;
|
||||
var multi = parsed.multi;
|
||||
var collation = parsed.collation;
|
||||
var arrayFilters = parsed.arrayFilters;
|
||||
var hint = parsed.hint;
|
||||
var rawData = parsed.rawData;
|
||||
let parsed = this._collection._parseUpdate.apply(this._collection, arguments);
|
||||
let query = parsed.query;
|
||||
let updateSpec = parsed.updateSpec;
|
||||
let upsert = parsed.upsert;
|
||||
let multi = parsed.multi;
|
||||
let collation = parsed.collation;
|
||||
let arrayFilters = parsed.arrayFilters;
|
||||
let hint = parsed.hint;
|
||||
let rawData = parsed.rawData;
|
||||
|
||||
var bulk = this._collection.initializeOrderedBulkOp();
|
||||
let bulk = this._collection.initializeOrderedBulkOp();
|
||||
|
||||
if (rawData) {
|
||||
bulk.setRawData(rawData);
|
||||
}
|
||||
|
||||
var updateOp = bulk.find(query);
|
||||
let updateOp = bulk.find(query);
|
||||
|
||||
if (hint) {
|
||||
updateOp.hint(hint);
|
||||
@ -243,8 +243,8 @@ function Explainable(collection, verbosity) {
|
||||
updateOp.updateOne(updateSpec);
|
||||
}
|
||||
|
||||
var explainCmd = bulk.convertToExplainCmd(this._verbosity);
|
||||
var explainResult = this._collection.runCommand(explainCmd);
|
||||
let explainCmd = bulk.convertToExplainCmd(this._verbosity);
|
||||
let explainResult = this._collection.runCommand(explainCmd);
|
||||
return throwOrReturn(explainResult);
|
||||
};
|
||||
|
||||
@ -378,7 +378,7 @@ function sbeReformatExperimental(explain, fieldsToKeep) {
|
||||
// callback is executed last on the root.
|
||||
function walkTree(root, callbackFn) {
|
||||
if ("inputStages" in root) {
|
||||
for (var i = 0; i < root.inputStages.length; i++) {
|
||||
for (let i = 0; i < root.inputStages.length; i++) {
|
||||
walkTree(root.inputStages[i], callbackFn);
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,15 +10,15 @@
|
||||
* multiple times.
|
||||
*/
|
||||
|
||||
var fcvConstants = getFCVConstants();
|
||||
let fcvConstants = getFCVConstants();
|
||||
|
||||
var latestFCV = fcvConstants.latest;
|
||||
var lastContinuousFCV = fcvConstants.lastContinuous;
|
||||
var lastLTSFCV = fcvConstants.lastLTS;
|
||||
let latestFCV = fcvConstants.latest;
|
||||
let lastContinuousFCV = fcvConstants.lastContinuous;
|
||||
let lastLTSFCV = fcvConstants.lastLTS;
|
||||
// The number of versions since the last-lts version. When numVersionsSinceLastLTS = 1,
|
||||
// lastContinuousFCV is equal to lastLTSFCV. This is used to calculate the expected minWireVersion
|
||||
// in jstests that use the lastLTSFCV.
|
||||
var numVersionsSinceLastLTS = fcvConstants.numSinceLastLTS;
|
||||
let numVersionsSinceLastLTS = fcvConstants.numSinceLastLTS;
|
||||
|
||||
/**
|
||||
* Returns the FCV associated with a binary version.
|
||||
|
||||
@ -31,7 +31,7 @@ class KeyVault {
|
||||
|
||||
constructor(mongo) {
|
||||
this.mongo = mongo;
|
||||
var collection = this._runCommand(this.mongo, this.mongo.getDataKeyCollection, {});
|
||||
let collection = this._runCommand(this.mongo, this.mongo.getDataKeyCollection, {});
|
||||
this.keyColl = collection;
|
||||
this._runCommand(this.keyColl, this.keyColl.createIndex, [
|
||||
{keyAltNames: 1},
|
||||
@ -59,14 +59,14 @@ class KeyVault {
|
||||
return "TypeError: customer master key must be of String type.";
|
||||
}
|
||||
|
||||
var masterKeyAndMaterial = this._runCommand(
|
||||
let masterKeyAndMaterial = this._runCommand(
|
||||
this.mongo, this.mongo.generateDataKey, [kmsProvider, customerMasterKey]);
|
||||
var masterKey = masterKeyAndMaterial.masterKey;
|
||||
let masterKey = masterKeyAndMaterial.masterKey;
|
||||
|
||||
var current = ISODate();
|
||||
var uuid = UUID();
|
||||
let current = ISODate();
|
||||
let uuid = UUID();
|
||||
|
||||
var doc = {
|
||||
let doc = {
|
||||
"_id": uuid,
|
||||
"keyMaterial": masterKeyAndMaterial.keyMaterial,
|
||||
"creationDate": current,
|
||||
|
||||
@ -174,12 +174,12 @@ Mongo.prototype.runCommand = function(dbname, cmd, options) {
|
||||
* Returns all log components and current verbosity values
|
||||
*/
|
||||
Mongo.prototype.getLogComponents = function(driverSession = this._getDefaultSession()) {
|
||||
var cmdObj = {getParameter: 1, logComponentVerbosity: 1};
|
||||
let cmdObj = {getParameter: 1, logComponentVerbosity: 1};
|
||||
if (driverSession._isExplicit || !jsTest.options().disableImplicitSessions) {
|
||||
cmdObj = driverSession._serverSession.injectSessionId(cmdObj);
|
||||
}
|
||||
|
||||
var res = this.adminCommand(cmdObj);
|
||||
let res = this.adminCommand(cmdObj);
|
||||
if (!res.ok)
|
||||
throw _getErrorWithCode(res, "getLogComponents failed:" + tojson(res));
|
||||
return res.logComponentVerbosity;
|
||||
@ -197,22 +197,22 @@ Mongo.prototype.setLogLevel = function(
|
||||
} else if (component !== undefined) {
|
||||
throw Error("setLogLevel component must be a string:" + tojson(component));
|
||||
}
|
||||
var vDoc = {verbosity: logLevel};
|
||||
let vDoc = {verbosity: logLevel};
|
||||
|
||||
// nest vDoc
|
||||
for (var key, obj; componentNames.length > 0;) {
|
||||
for (let key, obj; componentNames.length > 0;) {
|
||||
obj = {};
|
||||
key = componentNames.pop();
|
||||
obj[key] = vDoc;
|
||||
vDoc = obj;
|
||||
}
|
||||
|
||||
var cmdObj = {setParameter: 1, logComponentVerbosity: vDoc};
|
||||
let cmdObj = {setParameter: 1, logComponentVerbosity: vDoc};
|
||||
if (driverSession._isExplicit || !jsTest.options().disableImplicitSessions) {
|
||||
cmdObj = driverSession._serverSession.injectSessionId(cmdObj);
|
||||
}
|
||||
|
||||
var res = this.adminCommand(cmdObj);
|
||||
let res = this.adminCommand(cmdObj);
|
||||
if (!res.ok)
|
||||
throw _getErrorWithCode(res, "setLogLevel failed:" + tojson(res));
|
||||
return res;
|
||||
@ -225,11 +225,11 @@ Mongo.prototype.getDBNames = function() {
|
||||
};
|
||||
|
||||
Mongo.prototype.getCollection = function(ns) {
|
||||
var idx = ns.indexOf(".");
|
||||
let idx = ns.indexOf(".");
|
||||
if (idx < 0)
|
||||
throw Error("need . in ns");
|
||||
var db = ns.substring(0, idx);
|
||||
var c = ns.substring(idx + 1);
|
||||
let db = ns.substring(0, idx);
|
||||
let c = ns.substring(idx + 1);
|
||||
return this.getDB(db).getCollection(c);
|
||||
};
|
||||
|
||||
@ -325,7 +325,7 @@ globalThis.connect = function(url, user, pass, apiParameters) {
|
||||
// or "hostName/databaseName"
|
||||
// or "databaseName"
|
||||
// or full mongo uri.
|
||||
var urlType = typeof url;
|
||||
let urlType = typeof url;
|
||||
if (urlType == "undefined") {
|
||||
throw Error("Missing connection string");
|
||||
}
|
||||
@ -354,17 +354,18 @@ globalThis.connect = function(url, user, pass, apiParameters) {
|
||||
}
|
||||
}
|
||||
|
||||
var atPos = url.indexOf("@");
|
||||
var protocolPos = url.indexOf("://");
|
||||
var safeURL = url;
|
||||
let atPos = url.indexOf("@");
|
||||
let protocolPos = url.indexOf("://");
|
||||
let safeURL = url;
|
||||
if (atPos != -1 && protocolPos != -1) {
|
||||
safeURL = url.substring(0, protocolPos + 3) + url.substring(atPos + 1);
|
||||
}
|
||||
chatty("connecting to: " + safeURL);
|
||||
let m;
|
||||
try {
|
||||
var m = new Mongo(url, undefined /* encryptedDBClientCallback */, apiParameters);
|
||||
m = new Mongo(url, undefined /* encryptedDBClientCallback */, apiParameters);
|
||||
} catch (e) {
|
||||
var dest;
|
||||
let dest;
|
||||
if (url.indexOf(".query.mongodb.net") != -1) {
|
||||
dest = "MongoDB Atlas Data Lake";
|
||||
} else if (url.indexOf(".mongodb.net") != -1) {
|
||||
@ -378,7 +379,7 @@ globalThis.connect = function(url, user, pass, apiParameters) {
|
||||
|
||||
throw e;
|
||||
}
|
||||
var db = m.getDB(m.defaultDB);
|
||||
let db = m.getDB(m.defaultDB);
|
||||
|
||||
if (user && pass) {
|
||||
if (!db.auth(user, pass)) {
|
||||
@ -397,10 +398,10 @@ globalThis.connect = function(url, user, pass, apiParameters) {
|
||||
TestData = Object.merge(originalTestData, {disableImplicitSessions: true});
|
||||
try {
|
||||
// Check server version
|
||||
var serverVersion = db.version();
|
||||
let serverVersion = db.version();
|
||||
chatty("MongoDB server version: " + serverVersion);
|
||||
|
||||
var shellVersion = version();
|
||||
let shellVersion = version();
|
||||
if (serverVersion.slice(0, 3) != shellVersion.slice(0, 3)) {
|
||||
chatty("WARNING: shell and server versions do not match");
|
||||
}
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
var MongoRunner, _startMongod, startMongoProgram, runMongoProgram, startMongoProgramNoConnect,
|
||||
let MongoRunner, _startMongod, startMongoProgram, runMongoProgram, startMongoProgramNoConnect,
|
||||
myPort;
|
||||
|
||||
const SIGTERM = 15;
|
||||
|
||||
var shellVersion = version;
|
||||
let shellVersion = version;
|
||||
|
||||
// Record the exit codes of mongod and mongos processes that crashed during startup keyed by
|
||||
// port. This map is cleared when MongoRunner._startWithArgs and MongoRunner.stopMongod/s are
|
||||
// called.
|
||||
var serverExitCodeMap = {};
|
||||
var grpcToMongoRpcPortMap = {};
|
||||
let serverExitCodeMap = {};
|
||||
let grpcToMongoRpcPortMap = {};
|
||||
|
||||
var _parsePath = function() {
|
||||
var dbpath = "";
|
||||
for (var i = 0; i < arguments.length; ++i)
|
||||
let _parsePath = function() {
|
||||
let dbpath = "";
|
||||
for (let i = 0; i < arguments.length; ++i)
|
||||
if (arguments[i] == "--dbpath")
|
||||
dbpath = arguments[i + 1];
|
||||
|
||||
@ -23,23 +23,23 @@ var _parsePath = function() {
|
||||
return dbpath;
|
||||
};
|
||||
|
||||
var createMongoArgs = function(binaryName, args) {
|
||||
let createMongoArgs = function(binaryName, args) {
|
||||
if (!Array.isArray(args)) {
|
||||
throw new Error("The second argument to createMongoArgs must be an array");
|
||||
}
|
||||
|
||||
var fullArgs = [binaryName];
|
||||
let fullArgs = [binaryName];
|
||||
|
||||
if (args.length == 1 && isObject(args[0])) {
|
||||
var o = args[0];
|
||||
for (var k in o) {
|
||||
let o = args[0];
|
||||
for (let k in o) {
|
||||
if (o.hasOwnProperty(k)) {
|
||||
if (k == "v" && isNumber(o[k])) {
|
||||
var n = o[k];
|
||||
let n = o[k];
|
||||
if (n > 0) {
|
||||
if (n > 10)
|
||||
n = 10;
|
||||
var temp = "-";
|
||||
let temp = "-";
|
||||
while (n-- > 0)
|
||||
temp += "v";
|
||||
fullArgs.push(temp);
|
||||
@ -52,7 +52,7 @@ var createMongoArgs = function(binaryName, args) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (var i = 0; i < args.length; i++)
|
||||
for (let i = 0; i < args.length; i++)
|
||||
fullArgs.push(args[i]);
|
||||
}
|
||||
|
||||
@ -105,10 +105,10 @@ MongoRunner.getMongoShellPath = function() {
|
||||
};
|
||||
|
||||
MongoRunner.parsePort = function() {
|
||||
var port = "";
|
||||
let port = "";
|
||||
const portKey = jsTestOptions().shellGRPC ? "--grpcPort" : "--port";
|
||||
|
||||
for (var i = 0; i < arguments.length; ++i) {
|
||||
for (let i = 0; i < arguments.length; ++i) {
|
||||
if (arguments[i] == portKey) {
|
||||
port = arguments[i + 1];
|
||||
}
|
||||
@ -223,9 +223,9 @@ MongoRunner.runHangAnalyzer.disable = function() {
|
||||
* "3.2" -> [ "3", "2" ]
|
||||
* 3 -> exception: versions must have at least two components.
|
||||
*/
|
||||
var convertVersionStringToArray = function(versionString) {
|
||||
let convertVersionStringToArray = function(versionString) {
|
||||
assert("" !== versionString, "Version strings must not be empty");
|
||||
var versionArray = versionString.split('.');
|
||||
let versionArray = versionString.split('.');
|
||||
|
||||
assert.gt(versionArray.length,
|
||||
1,
|
||||
@ -238,7 +238,7 @@ var convertVersionStringToArray = function(versionString) {
|
||||
* Returns an integer
|
||||
* This function will not work if the minor version is greater than or equal to 10
|
||||
*/
|
||||
var convertVersionStringToInteger = function(versionString) {
|
||||
let convertVersionStringToInteger = function(versionString) {
|
||||
const [major, minor, point] = _convertVersionToIntegerArray(versionString);
|
||||
assert(
|
||||
minor < 10,
|
||||
@ -254,13 +254,13 @@ var convertVersionStringToInteger = function(versionString) {
|
||||
* 3.2 -> 3.2
|
||||
* 3 -> exception: versions must have at least two components.
|
||||
*/
|
||||
var extractMajorVersionFromVersionString = function(versionString) {
|
||||
let extractMajorVersionFromVersionString = function(versionString) {
|
||||
return convertVersionStringToArray(versionString).slice(0, 2).join('.');
|
||||
};
|
||||
|
||||
// These patterns allow substituting the binary versions used for each version string to support
|
||||
// the dev/stable MongoDB release cycle.
|
||||
var fcvConstants = getFCVConstants();
|
||||
let fcvConstants = getFCVConstants();
|
||||
|
||||
MongoRunner.binVersionSubs = [
|
||||
new MongoRunner.VersionSub("latest", shellVersion()),
|
||||
@ -281,8 +281,8 @@ MongoRunner.getBinVersionFor = function(version) {
|
||||
version = "latest";
|
||||
|
||||
// See if this version is affected by version substitutions
|
||||
for (var i = 0; i < MongoRunner.binVersionSubs.length; i++) {
|
||||
var sub = MongoRunner.binVersionSubs[i];
|
||||
for (let i = 0; i < MongoRunner.binVersionSubs.length; i++) {
|
||||
let sub = MongoRunner.binVersionSubs[i];
|
||||
if (sub.pattern == version) {
|
||||
return sub.version;
|
||||
}
|
||||
@ -331,18 +331,18 @@ MongoRunner.compareBinVersions = function(versionA, versionB) {
|
||||
versionA.push(...versionA.pop().split("-"));
|
||||
versionB.push(...versionB.pop().split("-"));
|
||||
|
||||
var elementsToCompare = Math.min(versionA.length, versionB.length);
|
||||
let elementsToCompare = Math.min(versionA.length, versionB.length);
|
||||
|
||||
for (var i = 0; i < elementsToCompare; ++i) {
|
||||
var elementA = versionA[i];
|
||||
var elementB = versionB[i];
|
||||
for (let i = 0; i < elementsToCompare; ++i) {
|
||||
let elementA = versionA[i];
|
||||
let elementB = versionB[i];
|
||||
|
||||
if (elementA === elementB) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var numA = parseInt(elementA);
|
||||
var numB = parseInt(elementB);
|
||||
let numA = parseInt(elementA);
|
||||
let numB = parseInt(elementB);
|
||||
|
||||
assert(!isNaN(numA) && !isNaN(numB),
|
||||
`Cannot compare non-equal non-numeric versions. ${elementA}, ${elementB}`);
|
||||
@ -392,7 +392,7 @@ MongoRunner.toRealPath = function(path, pathOpts) {
|
||||
pathOpts = pathOpts || {};
|
||||
path = path.replace(/\$dataPath/g, MongoRunner.dataPath);
|
||||
path = path.replace(/\$dataDir/g, MongoRunner.dataDir);
|
||||
for (var key in pathOpts) {
|
||||
for (let key in pathOpts) {
|
||||
path = path.replace(RegExp("\\$" + RegExp.escape(key), "g"), pathOpts[key]);
|
||||
}
|
||||
|
||||
@ -442,7 +442,7 @@ MongoRunner.versionIterator = function(arr, isRandom) {
|
||||
isRandom = false;
|
||||
|
||||
// Starting pos
|
||||
var i = isRandom ? parseInt(Random.rand() * arr.length) : 0;
|
||||
let i = isRandom ? parseInt(Random.rand() * arr.length) : 0;
|
||||
|
||||
return new MongoRunner.versionIterator.iterator(i, arr);
|
||||
};
|
||||
@ -480,12 +480,12 @@ MongoRunner.versionIterator.iterator = function(i, arr) {
|
||||
* to the binary.
|
||||
*/
|
||||
MongoRunner.arrOptions = function(binaryName, args) {
|
||||
var fullArgs = [""];
|
||||
let fullArgs = [""];
|
||||
|
||||
// isObject returns true even if "args" is an array, so the else branch of this statement is
|
||||
// dead code. See SERVER-14220.
|
||||
if (isObject(args) || (args.length == 1 && isObject(args[0]))) {
|
||||
var o = isObject(args) ? args : args[0];
|
||||
let o = isObject(args) ? args : args[0];
|
||||
|
||||
// If we've specified a particular binary version, use that
|
||||
if (o.binVersion && o.binVersion != "" && o.binVersion != shellVersion()) {
|
||||
@ -495,14 +495,14 @@ MongoRunner.arrOptions = function(binaryName, args) {
|
||||
}
|
||||
|
||||
// Manage legacy options
|
||||
var isValidOptionForBinary = function(option, value) {
|
||||
let isValidOptionForBinary = function(option, value) {
|
||||
if (!o.binVersion)
|
||||
return true;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
var addOptionsToFullArgs = function(k, v) {
|
||||
let addOptionsToFullArgs = function(k, v) {
|
||||
if (v === undefined || v === null)
|
||||
return;
|
||||
|
||||
@ -513,18 +513,18 @@ MongoRunner.arrOptions = function(binaryName, args) {
|
||||
}
|
||||
};
|
||||
|
||||
for (var k in o) {
|
||||
for (let k in o) {
|
||||
// Make sure our logical option should be added to the array of options
|
||||
if (!o.hasOwnProperty(k) || k in MongoRunner.logicalOptions ||
|
||||
!isValidOptionForBinary(k, o[k]))
|
||||
continue;
|
||||
|
||||
if ((k == "v" || k == "verbose") && isNumber(o[k])) {
|
||||
var n = o[k];
|
||||
let n = o[k];
|
||||
if (n > 0) {
|
||||
if (n > 10)
|
||||
n = 10;
|
||||
var temp = "-";
|
||||
let temp = "-";
|
||||
while (n-- > 0)
|
||||
temp += "v";
|
||||
fullArgs.push(temp);
|
||||
@ -544,7 +544,7 @@ MongoRunner.arrOptions = function(binaryName, args) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (var i = 0; i < args.length; i++)
|
||||
for (let i = 0; i < args.length; i++)
|
||||
fullArgs.push(args[i]);
|
||||
}
|
||||
|
||||
@ -553,10 +553,10 @@ MongoRunner.arrOptions = function(binaryName, args) {
|
||||
};
|
||||
|
||||
MongoRunner.arrToOpts = function(arr) {
|
||||
var opts = {};
|
||||
for (var i = 1; i < arr.length; i++) {
|
||||
let opts = {};
|
||||
for (let i = 1; i < arr.length; i++) {
|
||||
if (arr[i].startsWith("-")) {
|
||||
var opt = arr[i].replace(/^-/, "").replace(/^-/, "");
|
||||
let opt = arr[i].replace(/^-/, "").replace(/^-/, "");
|
||||
|
||||
if (arr.length > i + 1 && !arr[i + 1].startsWith("-")) {
|
||||
opts[opt] = arr[i + 1];
|
||||
@ -578,7 +578,7 @@ MongoRunner.savedOptions = {};
|
||||
|
||||
MongoRunner.mongoOptions = function(opts) {
|
||||
// Don't remember waitForConnect
|
||||
var waitForConnect = opts.waitForConnect;
|
||||
let waitForConnect = opts.waitForConnect;
|
||||
delete opts.waitForConnect;
|
||||
|
||||
// If we're a mongo object
|
||||
@ -669,7 +669,7 @@ MongoRunner.mongoOptions = function(opts) {
|
||||
opts.pathOpts =
|
||||
Object.merge(opts.pathOpts || {}, {port: "" + opts.port, runId: "" + opts.runId});
|
||||
|
||||
var shouldRemember =
|
||||
let shouldRemember =
|
||||
(!opts.restart && !opts.noRemember) || (opts.restart && opts.appendOptions);
|
||||
if (shouldRemember) {
|
||||
MongoRunner.savedOptions[opts.runId] = Object.merge(opts, {});
|
||||
@ -690,8 +690,8 @@ MongoRunner.mongoOptions = function(opts) {
|
||||
|
||||
// Returns an array of integers representing the version provided.
|
||||
// Ex: "3.3.12" => [3, 3, 12]
|
||||
var _convertVersionToIntegerArray = function(version) {
|
||||
var versionParts =
|
||||
function _convertVersionToIntegerArray(version) {
|
||||
let versionParts =
|
||||
convertVersionStringToArray(version).slice(0, 3).map(part => parseInt(part, 10));
|
||||
if (versionParts.length === 2) {
|
||||
versionParts.push(Infinity);
|
||||
@ -700,13 +700,13 @@ var _convertVersionToIntegerArray = function(version) {
|
||||
};
|
||||
|
||||
// Returns if version2 is equal to, or came after, version 1.
|
||||
var _isMongodVersionEqualOrAfter = function(version1, version2) {
|
||||
let _isMongodVersionEqualOrAfter = function(version1, version2) {
|
||||
if (version2 === "latest") {
|
||||
return true;
|
||||
}
|
||||
|
||||
var versionParts1 = _convertVersionToIntegerArray(version1);
|
||||
var versionParts2 = _convertVersionToIntegerArray(version2);
|
||||
let versionParts1 = _convertVersionToIntegerArray(version1);
|
||||
let versionParts2 = _convertVersionToIntegerArray(version2);
|
||||
if (versionParts2[0] > versionParts1[0] ||
|
||||
(versionParts2[0] === versionParts1[0] && versionParts2[1] > versionParts1[1]) ||
|
||||
(versionParts2[0] === versionParts1[0] && versionParts2[1] === versionParts1[1] &&
|
||||
@ -719,10 +719,10 @@ var _isMongodVersionEqualOrAfter = function(version1, version2) {
|
||||
|
||||
// Removes a setParameter parameter from mongods or mongoses running a version that won't recognize
|
||||
// them.
|
||||
var _removeSetParameterIfBeforeVersion = function(
|
||||
let _removeSetParameterIfBeforeVersion = function(
|
||||
opts, parameterName, requiredVersion, isMongos = false) {
|
||||
var processString = isMongos ? "mongos" : "mongod";
|
||||
var versionCompatible = (opts.binVersion === "" || opts.binVersion === undefined ||
|
||||
let processString = isMongos ? "mongos" : "mongod";
|
||||
let versionCompatible = (opts.binVersion === "" || opts.binVersion === undefined ||
|
||||
_isMongodVersionEqualOrAfter(requiredVersion, opts.binVersion));
|
||||
if (!versionCompatible && opts.setParameter && opts.setParameter[parameterName] != undefined) {
|
||||
print("Removing '" + parameterName + "' setParameter with value " +
|
||||
@ -912,7 +912,7 @@ MongoRunner.mongosOptions = function(opts) {
|
||||
opts.logpath = opts.logFile;
|
||||
}
|
||||
|
||||
var testOptions = jsTestOptions();
|
||||
let testOptions = jsTestOptions();
|
||||
if (testOptions.keyFile && !opts.keyFile) {
|
||||
opts.keyFile = testOptions.keyFile;
|
||||
}
|
||||
@ -981,12 +981,12 @@ MongoRunner.runningChildPids = function() {
|
||||
*/
|
||||
MongoRunner.runMongod = function(opts) {
|
||||
opts = opts || {};
|
||||
var env = undefined;
|
||||
var useHostName = true;
|
||||
var runId = null;
|
||||
var waitForConnect = true;
|
||||
var waitForConnectTimeoutMS = undefined;
|
||||
var fullOptions = opts;
|
||||
let env = undefined;
|
||||
let useHostName = true;
|
||||
let runId = null;
|
||||
let waitForConnect = true;
|
||||
let waitForConnectTimeoutMS = undefined;
|
||||
let fullOptions = opts;
|
||||
|
||||
if (isObject(opts)) {
|
||||
opts = MongoRunner.mongodOptions(opts);
|
||||
@ -1029,7 +1029,7 @@ MongoRunner.runMongod = function(opts) {
|
||||
opts = MongoRunner.arrOptions("mongod", opts);
|
||||
}
|
||||
|
||||
var mongod = MongoRunner._startWithArgs(opts, env, waitForConnect, waitForConnectTimeoutMS);
|
||||
let mongod = MongoRunner._startWithArgs(opts, env, waitForConnect, waitForConnectTimeoutMS);
|
||||
if (!mongod) {
|
||||
return null;
|
||||
}
|
||||
@ -1061,12 +1061,12 @@ MongoRunner.getMongosName = function(port, useHostName) {
|
||||
MongoRunner.runMongos = function(opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var env = undefined;
|
||||
var useHostName = false;
|
||||
var runId = null;
|
||||
var waitForConnect = true;
|
||||
var waitForConnectTimeoutMS = undefined;
|
||||
var fullOptions = opts;
|
||||
let env = undefined;
|
||||
let useHostName = false;
|
||||
let runId = null;
|
||||
let waitForConnect = true;
|
||||
let waitForConnectTimeoutMS = undefined;
|
||||
let fullOptions = opts;
|
||||
|
||||
if (isObject(opts)) {
|
||||
opts = MongoRunner.mongosOptions(opts);
|
||||
@ -1080,7 +1080,7 @@ MongoRunner.runMongos = function(opts) {
|
||||
opts = MongoRunner.arrOptions("mongos", opts);
|
||||
}
|
||||
|
||||
var mongos = MongoRunner._startWithArgs(opts, env, waitForConnect, waitForConnectTimeoutMS);
|
||||
let mongos = MongoRunner._startWithArgs(opts, env, waitForConnect, waitForConnectTimeoutMS);
|
||||
if (!mongos) {
|
||||
return null;
|
||||
}
|
||||
@ -1157,7 +1157,7 @@ MongoRunner.validateCollectionsCallback = function(port, options) {};
|
||||
* Note: The auth option is required in a authenticated mongod running in Windows since
|
||||
* it uses the shutdown command, which requires admin credentials.
|
||||
*/
|
||||
var stopMongoProgram = function(conn, signal, opts, waitpid) {
|
||||
let stopMongoProgram = function(conn, signal, opts, waitpid) {
|
||||
if (!conn.pid) {
|
||||
throw new Error("first arg must have a `pid` property; " +
|
||||
"it is usually the object returned from MongoRunner.runMongod/s");
|
||||
@ -1183,7 +1183,7 @@ var stopMongoProgram = function(conn, signal, opts, waitpid) {
|
||||
throw new Error('Must wait for process to exit if it is expected to exit uncleanly');
|
||||
}
|
||||
|
||||
var port = parseInt(conn.port);
|
||||
let port = parseInt(conn.port);
|
||||
|
||||
if (grpcToMongoRpcPortMap[port]) {
|
||||
port = grpcToMongoRpcPortMap[port];
|
||||
@ -1191,7 +1191,7 @@ var stopMongoProgram = function(conn, signal, opts, waitpid) {
|
||||
|
||||
// If the return code is in the serverExitCodeMap, it means the server crashed on startup.
|
||||
// We just use the recorded return code instead of stopping the program.
|
||||
var returnCode;
|
||||
let returnCode;
|
||||
if (serverExitCodeMap.hasOwnProperty(port)) {
|
||||
returnCode = serverExitCodeMap[port];
|
||||
delete serverExitCodeMap[port];
|
||||
@ -1200,7 +1200,7 @@ var stopMongoProgram = function(conn, signal, opts, waitpid) {
|
||||
// We skip calling the callback function when the expected return code of
|
||||
// the mongod process is non-zero since it's likely the process has already exited.
|
||||
|
||||
var skipValidation = false;
|
||||
let skipValidation = false;
|
||||
if (opts.skipValidation) {
|
||||
skipValidation = true;
|
||||
}
|
||||
@ -1232,7 +1232,7 @@ MongoRunner.stopMongos = stopMongoProgram;
|
||||
// Given a test name figures out a directory for that test to use for dump files and makes sure
|
||||
// that directory exists and is empty.
|
||||
MongoRunner.getAndPrepareDumpDirectory = function(testName) {
|
||||
var dir = MongoRunner.dataPath + testName + "_external/";
|
||||
let dir = MongoRunner.dataPath + testName + "_external/";
|
||||
resetDbpath(dir);
|
||||
return dir;
|
||||
};
|
||||
@ -1241,10 +1241,10 @@ MongoRunner.getAndPrepareDumpDirectory = function(testName) {
|
||||
// This function's arguments are passed as command line arguments to mongod.
|
||||
// The specified 'dbpath' is cleared if it exists, created if not.
|
||||
// var conn = _startMongodEmpty("--port", 30000, "--dbpath", "asdf");
|
||||
var _startMongodEmpty = function() {
|
||||
var args = createMongoArgs("mongod", Array.from(arguments));
|
||||
let _startMongodEmpty = function() {
|
||||
let args = createMongoArgs("mongod", Array.from(arguments));
|
||||
|
||||
var dbpath = _parsePath.apply(null, args);
|
||||
let dbpath = _parsePath.apply(null, args);
|
||||
resetDbpath(dbpath);
|
||||
|
||||
return startMongoProgram.apply(null, args);
|
||||
@ -1602,14 +1602,14 @@ function appendSetParameterArgs(argArray) {
|
||||
MongoRunner.awaitConnection = function({pid, port, waitTimeoutMS} = {
|
||||
waitTimeoutMS: 600 * 1000
|
||||
}) {
|
||||
var conn = null;
|
||||
let conn = null;
|
||||
assert.soon(function() {
|
||||
try {
|
||||
conn = new Mongo("127.0.0.1:" + port);
|
||||
conn.pid = pid;
|
||||
return true;
|
||||
} catch (e) {
|
||||
var res = checkProgram(pid);
|
||||
let res = checkProgram(pid);
|
||||
if (!res.alive) {
|
||||
print("mongo program was not running at " + port +
|
||||
", process ended with exit code: " + res.exitCode);
|
||||
@ -1642,8 +1642,8 @@ MongoRunner._startWithArgs = function(argArray, env, waitForConnect, waitForConn
|
||||
"runMongo*() cannot be used with a fuzzed configuration, use standalone.py instead.");
|
||||
|
||||
argArray = appendSetParameterArgs(argArray);
|
||||
var port = MongoRunner.parsePort.apply(null, argArray);
|
||||
var pid = -1;
|
||||
let port = MongoRunner.parsePort.apply(null, argArray);
|
||||
let pid = -1;
|
||||
|
||||
if (jsTest.options().mozJSGCZeal) {
|
||||
if (env === undefined) {
|
||||
@ -1680,23 +1680,23 @@ MongoRunner._startWithArgs = function(argArray, env, waitForConnect, waitForConn
|
||||
* command line arguments to the program.
|
||||
*/
|
||||
startMongoProgram = function() {
|
||||
var port = MongoRunner.parsePort.apply(null, arguments);
|
||||
let port = MongoRunner.parsePort.apply(null, arguments);
|
||||
|
||||
// Enable test commands.
|
||||
// TODO: Make this work better with multi-version testing so that we can support
|
||||
// enabling this on 2.4 when testing 2.6
|
||||
var args = Array.from(arguments);
|
||||
let args = Array.from(arguments);
|
||||
args = appendSetParameterArgs(args);
|
||||
var pid = _startMongoProgram.apply(null, args);
|
||||
let pid = _startMongoProgram.apply(null, args);
|
||||
|
||||
var m;
|
||||
let m;
|
||||
assert.soon(function() {
|
||||
try {
|
||||
m = new Mongo("127.0.0.1:" + port);
|
||||
m.pid = pid;
|
||||
return true;
|
||||
} catch (e) {
|
||||
var res = checkProgram(pid);
|
||||
let res = checkProgram(pid);
|
||||
if (!res.alive) {
|
||||
print("Could not start mongo program at " + port +
|
||||
", process ended with exit code: " + res.exitCode);
|
||||
@ -1714,7 +1714,7 @@ startMongoProgram = function() {
|
||||
function _getMongoProgramArguments(args) {
|
||||
args = Array.from(args);
|
||||
appendSetParameterArgs(args);
|
||||
var progName = args[0];
|
||||
let progName = args[0];
|
||||
|
||||
const separator = _isWindows() ? '\\' : '/';
|
||||
progName = progName.split(separator).pop();
|
||||
|
||||
@ -14,7 +14,7 @@ function ToolTest(name, extraOptions) {
|
||||
ToolTest.prototype.startDB = function(coll) {
|
||||
assert(!this.m, "db already running");
|
||||
|
||||
var options = {port: this.port, dbpath: this.dbpath, bind_ip: "127.0.0.1"};
|
||||
let options = {port: this.port, dbpath: this.dbpath, bind_ip: "127.0.0.1"};
|
||||
|
||||
Object.extend(options, this.options);
|
||||
|
||||
@ -36,12 +36,12 @@ ToolTest.prototype.stop = function() {
|
||||
};
|
||||
|
||||
ToolTest.prototype.runTool = function() {
|
||||
var a = ["mongo" + arguments[0]];
|
||||
let a = ["mongo" + arguments[0]];
|
||||
|
||||
var hasdbpath = false;
|
||||
var hasDialTimeout = false;
|
||||
let hasdbpath = false;
|
||||
let hasDialTimeout = false;
|
||||
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
for (let i = 1; i < arguments.length; i++) {
|
||||
a.push(arguments[i]);
|
||||
if (arguments[i] === "--dbpath")
|
||||
hasdbpath = true;
|
||||
@ -62,13 +62,13 @@ ToolTest.prototype.runTool = function() {
|
||||
return runMongoProgram.apply(null, a);
|
||||
};
|
||||
|
||||
var uncheckedParallelShellPids;
|
||||
let uncheckedParallelShellPids;
|
||||
|
||||
// Defer initializing these variables until the first call, as TestData attributes may be
|
||||
// initialized as part of the --eval argument (e.g. by resmoke.py), which will not be evaluated
|
||||
// until after this has loaded.
|
||||
var maxPort;
|
||||
var nextPort;
|
||||
let maxPort;
|
||||
let nextPort;
|
||||
|
||||
/**
|
||||
* Returns a port number that has not been given out to any other caller from the same mongo shell.
|
||||
@ -98,14 +98,14 @@ function resetAllocatedPorts() {
|
||||
maxPort = nextPort = undefined;
|
||||
};
|
||||
|
||||
var parallelShellPids = [];
|
||||
let parallelShellPids = [];
|
||||
function uncheckedParallelShellPidsString() {
|
||||
return parallelShellPids.join(", ");
|
||||
};
|
||||
|
||||
function startParallelShell(jsCode, port, noConnect, ...optionArgs) {
|
||||
var shellPath = MongoRunner.getMongoShellPath();
|
||||
var args = [shellPath];
|
||||
let shellPath = MongoRunner.getMongoShellPath();
|
||||
let args = [shellPath];
|
||||
|
||||
if (typeof globalThis.db === "object") {
|
||||
if (!port) {
|
||||
@ -114,7 +114,7 @@ function startParallelShell(jsCode, port, noConnect, ...optionArgs) {
|
||||
} else {
|
||||
// Strip port numbers from connect string.
|
||||
const uri = new MongoURI(globalThis.db.getMongo().host);
|
||||
var connString = uri.servers
|
||||
let connString = uri.servers
|
||||
.map(function(server) {
|
||||
return server.host;
|
||||
})
|
||||
@ -158,7 +158,7 @@ function startParallelShell(jsCode, port, noConnect, ...optionArgs) {
|
||||
args.push(...optionArgs);
|
||||
args.push("--eval", jsCode);
|
||||
|
||||
var pid = startMongoProgramNoConnect.apply(null, args);
|
||||
let pid = startMongoProgramNoConnect.apply(null, args);
|
||||
parallelShellPids.push(pid);
|
||||
|
||||
// Returns a function that when called waits for the parallel shell to exit and returns the exit
|
||||
@ -173,8 +173,8 @@ function startParallelShell(jsCode, port, noConnect, ...optionArgs) {
|
||||
throw new Error("options cannot be null");
|
||||
}
|
||||
}
|
||||
var exitCode = waitProgram(pid);
|
||||
var pidIndex = parallelShellPids.indexOf(pid);
|
||||
let exitCode = waitProgram(pid);
|
||||
let pidIndex = parallelShellPids.indexOf(pid);
|
||||
parallelShellPids.splice(pidIndex);
|
||||
if (arguments.length === 0 || options.checkExitSuccess) {
|
||||
assert.eq(0, exitCode, "encountered an error in the parallel shell");
|
||||
@ -188,15 +188,15 @@ function startParallelShell(jsCode, port, noConnect, ...optionArgs) {
|
||||
* the same mongo shell.
|
||||
*/
|
||||
function allocatePorts(numPorts) {
|
||||
var ports = [];
|
||||
for (var i = 0; i < numPorts; i++) {
|
||||
let ports = [];
|
||||
for (let i = 0; i < numPorts; i++) {
|
||||
ports.push(allocatePort());
|
||||
}
|
||||
|
||||
return ports;
|
||||
};
|
||||
|
||||
var testingReplication = false;
|
||||
let testingReplication = false;
|
||||
|
||||
export {
|
||||
ToolTest,
|
||||
|
||||
@ -819,7 +819,7 @@ ServerSession.canRetryWrites = function canRetryWrites(cmdObj) {
|
||||
};
|
||||
|
||||
function makeDriverSessionConstructor(implMethods, defaultOptions = {}) {
|
||||
var driverSessionConstructor = function(client, options = defaultOptions) {
|
||||
let driverSessionConstructor = function(client, options = defaultOptions) {
|
||||
const sessionAwareClient = new SessionAwareClient(client);
|
||||
|
||||
let _options = options;
|
||||
|
||||
@ -19,7 +19,7 @@ function reconnect(db) {
|
||||
}
|
||||
|
||||
function _getErrorWithCode(codeOrObj, message) {
|
||||
var e = new Error(message);
|
||||
let e = new Error(message);
|
||||
if (typeof codeOrObj === "object" && codeOrObj !== null) {
|
||||
if (TestData?.logFormat === "json") {
|
||||
e.extraAttr = codeOrObj;
|
||||
@ -259,7 +259,7 @@ function friendlyEqual(a, b) {
|
||||
if (a == b)
|
||||
return true;
|
||||
|
||||
var clean = function(s) {
|
||||
let clean = function(s) {
|
||||
s = s.replace(/NumberInt\((\-?\d+)\)/g, "$1");
|
||||
return s;
|
||||
};
|
||||
@ -300,10 +300,10 @@ function setVerboseShell(value) {
|
||||
// e.g. _barFormat([[.3, "="], [.5, '-']], 80) returns
|
||||
// "[========================---------------------------------------- ]"
|
||||
function _barFormat(data, width) {
|
||||
var remaining = width;
|
||||
var res = "[";
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
for (var x = 0; x < data[i][0] * width; x++) {
|
||||
let remaining = width;
|
||||
let res = "[";
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
for (let x = 0; x < data[i][0] * width; x++) {
|
||||
if (remaining-- > 0) {
|
||||
res += data[i][1];
|
||||
}
|
||||
@ -344,9 +344,9 @@ function enablePrint() {
|
||||
};
|
||||
|
||||
print.captureAllOutput = function(fn, args) {
|
||||
var res = {};
|
||||
let res = {};
|
||||
res.output = [];
|
||||
var __orig_print = print;
|
||||
let __orig_print = print;
|
||||
print = function() {
|
||||
Array.prototype.push.apply(res.output,
|
||||
Array.prototype.slice.call(arguments).join(" ").split("\n"));
|
||||
@ -360,7 +360,7 @@ print.captureAllOutput = function(fn, args) {
|
||||
return res;
|
||||
};
|
||||
|
||||
var indentStr = function(indent, s) {
|
||||
let indentStr = function(indent, s) {
|
||||
if (typeof (s) === "undefined") {
|
||||
s = indent;
|
||||
indent = 0;
|
||||
@ -411,7 +411,7 @@ function jsTestName() {
|
||||
return "__unknown_name__";
|
||||
};
|
||||
|
||||
var _jsTestOptions = {};
|
||||
let _jsTestOptions = {};
|
||||
|
||||
function jsTestOptions() {
|
||||
if (TestData) {
|
||||
@ -683,7 +683,7 @@ jsTest.authenticate = function(conn) {
|
||||
|
||||
jsTest.authenticateNodes = function(nodes) {
|
||||
assert.soonNoExcept(function() {
|
||||
for (var i = 0; i < nodes.length; i++) {
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
// Don't try to authenticate to arbiters
|
||||
let res = {};
|
||||
try {
|
||||
@ -711,12 +711,13 @@ jsTest.isMongos = function(conn) {
|
||||
};
|
||||
|
||||
function defaultPrompt() {
|
||||
var status = globalThis.db.getMongo().authStatus;
|
||||
var prefix = globalThis.db.getMongo().promptPrefix;
|
||||
let status = globalThis.db.getMongo().authStatus;
|
||||
let prefix = globalThis.db.getMongo().promptPrefix;
|
||||
let hello;
|
||||
|
||||
if (typeof prefix == 'undefined') {
|
||||
prefix = "";
|
||||
var buildInfo = globalThis.db._runCommandWithoutApiStrict({buildInfo: 1});
|
||||
let buildInfo = globalThis.db._runCommandWithoutApiStrict({buildInfo: 1});
|
||||
try {
|
||||
if (buildInfo.modules.indexOf("enterprise") > -1) {
|
||||
prefix += "MongoDB Enterprise ";
|
||||
@ -724,7 +725,7 @@ function defaultPrompt() {
|
||||
} catch (e) {
|
||||
// Don't do anything here. Just throw the error away.
|
||||
}
|
||||
var hello = globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
hello = globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
try {
|
||||
if (hello.hasOwnProperty("automationServiceDescriptor")) {
|
||||
prefix += "[automated] ";
|
||||
@ -739,7 +740,7 @@ function defaultPrompt() {
|
||||
// try to use repl set prompt -- no status or auth detected yet
|
||||
if (!status || !status.authRequired) {
|
||||
try {
|
||||
var prompt = replSetMemberStatePrompt();
|
||||
let prompt = replSetMemberStatePrompt();
|
||||
// set our status that it was good
|
||||
globalThis.db.getMongo().authStatus = {replSetGetStatus: true, hello: true};
|
||||
return prefix + prompt;
|
||||
@ -754,7 +755,7 @@ function defaultPrompt() {
|
||||
// try to use replSetGetStatus?
|
||||
if (status.replSetGetStatus) {
|
||||
try {
|
||||
var prompt = replSetMemberStatePrompt();
|
||||
let prompt = replSetMemberStatePrompt();
|
||||
// set our status that it was good
|
||||
status.replSetGetStatus = true;
|
||||
globalThis.db.getMongo().authStatus = status;
|
||||
@ -770,7 +771,7 @@ function defaultPrompt() {
|
||||
// try to use hello?
|
||||
if (status.hello) {
|
||||
try {
|
||||
var prompt = helloStatePrompt(hello);
|
||||
let prompt = helloStatePrompt(hello);
|
||||
status.hello = true;
|
||||
globalThis.db.getMongo().authStatus = status;
|
||||
return prefix + prompt;
|
||||
@ -790,8 +791,8 @@ function defaultPrompt() {
|
||||
};
|
||||
|
||||
function replSetMemberStatePrompt() {
|
||||
var state = '';
|
||||
var stateInfo = globalThis.db.getSiblingDB('admin')._runCommandWithoutApiStrict(
|
||||
let state = '';
|
||||
let stateInfo = globalThis.db.getSiblingDB('admin')._runCommandWithoutApiStrict(
|
||||
{replSetGetStatus: 1, forShell: 1});
|
||||
if (stateInfo.ok) {
|
||||
// Report the self member's stateStr if it's present.
|
||||
@ -806,7 +807,7 @@ function replSetMemberStatePrompt() {
|
||||
}
|
||||
state = '' + stateInfo.set + ':' + state;
|
||||
} else {
|
||||
var info = stateInfo.info;
|
||||
let info = stateInfo.info;
|
||||
if (info && info.length < 20) {
|
||||
state = info; // "mongos", "configsvr"
|
||||
} else {
|
||||
@ -817,10 +818,10 @@ function replSetMemberStatePrompt() {
|
||||
};
|
||||
|
||||
function helloStatePrompt(helloReply) {
|
||||
var state = '';
|
||||
var hello = helloReply || globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
let state = '';
|
||||
let hello = helloReply || globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
if (hello.ok) {
|
||||
var role = "";
|
||||
let role = "";
|
||||
|
||||
if (hello.msg == "isdbgrid") {
|
||||
role = "mongos";
|
||||
@ -878,11 +879,11 @@ function shellPrintHelper(x) {
|
||||
if (typeof x != "object")
|
||||
return print(x);
|
||||
|
||||
var p = x.shellPrint;
|
||||
let p = x.shellPrint;
|
||||
if (typeof p == "function")
|
||||
return x.shellPrint();
|
||||
|
||||
var p = x.tojson;
|
||||
p = x.tojson;
|
||||
if (typeof p == "function")
|
||||
print(x.tojson());
|
||||
else
|
||||
@ -891,11 +892,11 @@ function shellPrintHelper(x) {
|
||||
|
||||
let shellAutocomplete = function(
|
||||
/*prefix*/) { // outer scope function called on init. Actual function at end
|
||||
var universalMethods =
|
||||
let universalMethods =
|
||||
"constructor prototype toString valueOf toLocaleString hasOwnProperty propertyIsEnumerable"
|
||||
.split(' ');
|
||||
|
||||
var builtinMethods = {}; // uses constructor objects as keys
|
||||
let builtinMethods = {}; // uses constructor objects as keys
|
||||
builtinMethods[Array] =
|
||||
"length concat join pop push reverse shift slice sort splice unshift indexOf lastIndexOf every filter forEach map some isArray reduce reduceRight"
|
||||
.split(' ');
|
||||
@ -925,14 +926,14 @@ let shellAutocomplete = function(
|
||||
builtinMethods[Mongo] = "find update insert remove".split(' ');
|
||||
builtinMethods[BinData] = "hex base64 length subtype".split(' ');
|
||||
|
||||
var extraGlobals =
|
||||
let extraGlobals =
|
||||
"Infinity NaN undefined null true false decodeURI decodeURIComponent encodeURI encodeURIComponent escape eval isFinite isNaN parseFloat parseInt unescape Array Boolean Date Math Number RegExp String print load gc MinKey MaxKey Mongo NumberInt NumberLong ObjectId DBPointer UUID BinData HexData MD5 Map Timestamp JSON"
|
||||
.split(' ');
|
||||
if (typeof NumberDecimal !== 'undefined') {
|
||||
extraGlobals[extraGlobals.length] = "NumberDecimal";
|
||||
}
|
||||
|
||||
var isPrivate = function(name) {
|
||||
let isPrivate = function(name) {
|
||||
if (shellAutocomplete.showPrivate)
|
||||
return false;
|
||||
if (name == '_id')
|
||||
@ -944,10 +945,10 @@ let shellAutocomplete = function(
|
||||
return false;
|
||||
};
|
||||
|
||||
var customComplete = function(obj) {
|
||||
let customComplete = function(obj) {
|
||||
try {
|
||||
if (obj.__proto__.constructor.autocomplete) {
|
||||
var ret = obj.constructor.autocomplete(obj);
|
||||
let ret = obj.constructor.autocomplete(obj);
|
||||
if (ret.constructor != Array) {
|
||||
print("\nautocompleters must return real Arrays");
|
||||
return [];
|
||||
@ -962,24 +963,24 @@ let shellAutocomplete = function(
|
||||
}
|
||||
};
|
||||
|
||||
var worker = function(prefix) {
|
||||
var global = globalThis;
|
||||
let worker = function(prefix) {
|
||||
let global = globalThis;
|
||||
|
||||
var curObj = global;
|
||||
var parts = prefix.split('.');
|
||||
for (var p = 0; p < parts.length - 1; p++) { // doesn't include last part
|
||||
let curObj = global;
|
||||
let parts = prefix.split('.');
|
||||
for (let p = 0; p < parts.length - 1; p++) { // doesn't include last part
|
||||
curObj = curObj[parts[p]];
|
||||
if (curObj == null)
|
||||
return [];
|
||||
}
|
||||
|
||||
var lastPrefix = parts[parts.length - 1] || '';
|
||||
var lastPrefixLowercase = lastPrefix.toLowerCase();
|
||||
var beginning = parts.slice(0, parts.length - 1).join('.');
|
||||
let lastPrefix = parts[parts.length - 1] || '';
|
||||
let lastPrefixLowercase = lastPrefix.toLowerCase();
|
||||
let beginning = parts.slice(0, parts.length - 1).join('.');
|
||||
if (beginning.length)
|
||||
beginning += '.';
|
||||
|
||||
var possibilities =
|
||||
let possibilities =
|
||||
new Array().concat(universalMethods,
|
||||
Object.keySet(curObj),
|
||||
Object.keySet(curObj.__proto__),
|
||||
@ -989,10 +990,10 @@ let shellAutocomplete = function(
|
||||
curObj == global ? extraGlobals : [],
|
||||
customComplete(curObj));
|
||||
|
||||
var noDuplicates =
|
||||
let noDuplicates =
|
||||
{}; // see http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
|
||||
for (var i = 0; i < possibilities.length; i++) {
|
||||
var p = possibilities[i];
|
||||
for (let i = 0; i < possibilities.length; i++) {
|
||||
let p = possibilities[i];
|
||||
if (typeof (curObj[p]) == "undefined" && curObj != global)
|
||||
continue; // extraGlobals aren't in the global object
|
||||
if (p.length == 0 || p.length < lastPrefix.length)
|
||||
@ -1004,15 +1005,15 @@ let shellAutocomplete = function(
|
||||
if (p.substr(0, lastPrefix.length).toLowerCase() != lastPrefixLowercase)
|
||||
continue;
|
||||
|
||||
var completion = beginning + p;
|
||||
let completion = beginning + p;
|
||||
if (curObj[p] && curObj[p].constructor == Function && p != 'constructor')
|
||||
completion += '(';
|
||||
|
||||
noDuplicates[completion] = 0;
|
||||
}
|
||||
|
||||
var ret = [];
|
||||
for (var i in noDuplicates)
|
||||
let ret = [];
|
||||
for (let i in noDuplicates)
|
||||
ret.push(i);
|
||||
|
||||
return ret;
|
||||
@ -1033,12 +1034,12 @@ shellAutocomplete.showPrivate = false; // toggle to show (useful when working o
|
||||
|
||||
function shellHelper(command, rest, shouldPrint) {
|
||||
command = command.trim();
|
||||
var args = rest.trim().replace(/\s*;$/, "").split("\s+");
|
||||
let args = rest.trim().replace(/\s*;$/, "").split("\s+");
|
||||
|
||||
if (!shellHelper[command])
|
||||
throw Error("no command [" + command + "]");
|
||||
|
||||
var res = shellHelper[command].apply(null, args);
|
||||
let res = shellHelper[command].apply(null, args);
|
||||
if (shouldPrint) {
|
||||
shellPrintHelper(res);
|
||||
}
|
||||
@ -1046,7 +1047,7 @@ function shellHelper(command, rest, shouldPrint) {
|
||||
};
|
||||
|
||||
shellHelper.use = function(dbname) {
|
||||
var s = "" + dbname;
|
||||
let s = "" + dbname;
|
||||
if (s == "") {
|
||||
print("bad use parameter");
|
||||
return;
|
||||
@ -1089,11 +1090,11 @@ shellHelper.it = function() {
|
||||
shellHelper.show = function(what) {
|
||||
assert(typeof what == "string");
|
||||
|
||||
var args = what.split(/\s+/);
|
||||
let args = what.split(/\s+/);
|
||||
what = args[0];
|
||||
args = args.splice(1);
|
||||
|
||||
var messageIndent = " ";
|
||||
let messageIndent = " ";
|
||||
|
||||
if (what == "profile") {
|
||||
if (globalThis.db.system.profile.count() == 0) {
|
||||
@ -1108,13 +1109,13 @@ shellHelper.show = function(what) {
|
||||
.forEach(function(x) {
|
||||
print("" + x.op + "\t" + x.ns + " " + x.millis + "ms " +
|
||||
String(x.ts).substring(0, 24));
|
||||
var l = "";
|
||||
for (var z in x) {
|
||||
let l = "";
|
||||
for (let z in x) {
|
||||
if (z == "op" || z == "ns" || z == "millis" || z == "ts")
|
||||
continue;
|
||||
|
||||
var val = x[z];
|
||||
var mytype = typeof (val);
|
||||
let val = x[z];
|
||||
let mytype = typeof (val);
|
||||
|
||||
if (mytype == "string" || mytype == "number")
|
||||
l += z + ":" + val + " ";
|
||||
@ -1150,8 +1151,8 @@ shellHelper.show = function(what) {
|
||||
}
|
||||
|
||||
if (what == "dbs" || what == "databases") {
|
||||
var mongo = globalThis.db.getMongo();
|
||||
var dbs;
|
||||
let mongo = globalThis.db.getMongo();
|
||||
let dbs;
|
||||
try {
|
||||
dbs = mongo.getDBs(globalThis.db.getSession(), undefined, false);
|
||||
} catch (ex) {
|
||||
@ -1162,14 +1163,14 @@ shellHelper.show = function(what) {
|
||||
return "";
|
||||
}
|
||||
|
||||
var dbinfo = [];
|
||||
var maxNameLength = 0;
|
||||
var maxGbDigits = 0;
|
||||
let dbinfo = [];
|
||||
let maxNameLength = 0;
|
||||
let maxGbDigits = 0;
|
||||
|
||||
dbs.databases.forEach(function(x) {
|
||||
var sizeStr = (x.sizeOnDisk / 1024 / 1024 / 1024).toFixed(3);
|
||||
var nameLength = x.name.length;
|
||||
var gbDigits = sizeStr.indexOf(".");
|
||||
let sizeStr = (x.sizeOnDisk / 1024 / 1024 / 1024).toFixed(3);
|
||||
let nameLength = x.name.length;
|
||||
let gbDigits = sizeStr.indexOf(".");
|
||||
|
||||
if (nameLength > maxNameLength)
|
||||
maxNameLength = nameLength;
|
||||
@ -1188,9 +1189,9 @@ shellHelper.show = function(what) {
|
||||
|
||||
dbinfo.sort(compareOn('name'));
|
||||
dbinfo.forEach(function(db) {
|
||||
var namePadding = maxNameLength - db.name_size;
|
||||
var sizePadding = maxGbDigits - db.gb_digits;
|
||||
var padding = Array(namePadding + sizePadding + 3).join(" ");
|
||||
let namePadding = maxNameLength - db.name_size;
|
||||
let sizePadding = maxGbDigits - db.gb_digits;
|
||||
let padding = Array(namePadding + sizePadding + 3).join(" ");
|
||||
if (db.size > 1) {
|
||||
print(db.name + padding + db.size_str + "GB");
|
||||
} else if (db.empty) {
|
||||
@ -1204,35 +1205,35 @@ shellHelper.show = function(what) {
|
||||
}
|
||||
|
||||
if (what == "log") {
|
||||
var n = "global";
|
||||
let n = "global";
|
||||
if (args.length > 0)
|
||||
n = args[0];
|
||||
|
||||
var res = globalThis.db.adminCommand({getLog: n});
|
||||
let res = globalThis.db.adminCommand({getLog: n});
|
||||
if (!res.ok) {
|
||||
print("Error while trying to show " + n + " log: " + res.errmsg);
|
||||
return "";
|
||||
}
|
||||
for (var i = 0; i < res.log.length; i++) {
|
||||
for (let i = 0; i < res.log.length; i++) {
|
||||
print(res.log[i]);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
if (what == "logs") {
|
||||
var res = globalThis.db.adminCommand({getLog: "*"});
|
||||
let res = globalThis.db.adminCommand({getLog: "*"});
|
||||
if (!res.ok) {
|
||||
print("Error while trying to show logs: " + res.errmsg);
|
||||
return "";
|
||||
}
|
||||
for (var i = 0; i < res.names.length; i++) {
|
||||
for (let i = 0; i < res.names.length; i++) {
|
||||
print(res.names[i]);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
if (what == "startupWarnings") {
|
||||
var dbDeclared, ex;
|
||||
let dbDeclared, ex;
|
||||
try {
|
||||
// !!db essentially casts db to a boolean
|
||||
// Will throw a reference exception if db hasn't been declared.
|
||||
@ -1241,7 +1242,7 @@ shellHelper.show = function(what) {
|
||||
dbDeclared = false;
|
||||
}
|
||||
if (dbDeclared) {
|
||||
var res = globalThis.db.getSiblingDB("admin")._runCommandWithoutApiStrict(
|
||||
let res = globalThis.db.getSiblingDB("admin")._runCommandWithoutApiStrict(
|
||||
{getLog: "startupWarnings"});
|
||||
if (res.ok) {
|
||||
if (res.log.length == 0) {
|
||||
@ -1249,14 +1250,14 @@ shellHelper.show = function(what) {
|
||||
}
|
||||
print("---");
|
||||
print("The server generated these startup warnings when booting: ");
|
||||
for (var i = 0; i < res.log.length; i++) {
|
||||
var logOut;
|
||||
for (let i = 0; i < res.log.length; i++) {
|
||||
let logOut;
|
||||
try {
|
||||
var parsedLog = JSON.parse(res.log[i]);
|
||||
var linePrefix = messageIndent + parsedLog.t["$date"] + ": ";
|
||||
let parsedLog = JSON.parse(res.log[i]);
|
||||
let linePrefix = messageIndent + parsedLog.t["$date"] + ": ";
|
||||
logOut = linePrefix + parsedLog.msg + "\n";
|
||||
if (parsedLog.attr) {
|
||||
for (var attr in parsedLog.attr) {
|
||||
for (let attr in parsedLog.attr) {
|
||||
logOut += linePrefix + messageIndent + attr + ": " +
|
||||
parsedLog.attr[attr] + "\n";
|
||||
}
|
||||
@ -1287,7 +1288,7 @@ shellHelper.show = function(what) {
|
||||
}
|
||||
|
||||
if (what == "automationNotices") {
|
||||
var dbDeclared, ex;
|
||||
let dbDeclared, ex;
|
||||
try {
|
||||
// !!db essentially casts db to a boolean
|
||||
// Will throw a reference exception if db hasn't been declared.
|
||||
@ -1297,7 +1298,7 @@ shellHelper.show = function(what) {
|
||||
}
|
||||
|
||||
if (dbDeclared) {
|
||||
var res = globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
let res = globalThis.db._helloOrLegacyHello({forShell: 1});
|
||||
if (!res.ok) {
|
||||
print("Note: Cannot determine if automation is active");
|
||||
return "";
|
||||
@ -1396,13 +1397,13 @@ Math.sigFig = function(x, N) {
|
||||
if (!N) {
|
||||
N = 3;
|
||||
}
|
||||
var p = Math.pow(10, N - Math.ceil(Math.log(Math.abs(x)) / Math.log(10)));
|
||||
let p = Math.pow(10, N - Math.ceil(Math.log(Math.abs(x)) / Math.log(10)));
|
||||
return Math.round(x * p) / p;
|
||||
};
|
||||
|
||||
var Random = (function() {
|
||||
var initialized = false;
|
||||
var errorMsg = "The random number generator hasn't been seeded yet; " +
|
||||
let Random = (function() {
|
||||
let initialized = false;
|
||||
let errorMsg = "The random number generator hasn't been seeded yet; " +
|
||||
"call Random.setRandomSeed()";
|
||||
|
||||
function isInitialized() {
|
||||
@ -1417,14 +1418,14 @@ var Random = (function() {
|
||||
|
||||
// Set the random generator seed & print the result.
|
||||
function setRandomSeed(s) {
|
||||
var seed = srand(s);
|
||||
let seed = srand(s);
|
||||
print("setting random seed: " + seed);
|
||||
return seed;
|
||||
}
|
||||
|
||||
// Set the random generator seed with defined seed if it exists or a random seed if it does not.
|
||||
function setRandomFixtureSeed() {
|
||||
var seed = setRandomSeed(TestData.seed).valueOf();
|
||||
let seed = setRandomSeed(TestData.seed).valueOf();
|
||||
print(
|
||||
`Reproduce this randomized jstest fixture topology by adding the --shellSeed
|
||||
${seed} option to your resmoke invocation.`);
|
||||
@ -1454,7 +1455,7 @@ var Random = (function() {
|
||||
if (!initialized) {
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
var r = rand();
|
||||
let r = rand();
|
||||
if (r == 0) {
|
||||
r = rand();
|
||||
if (r == 0) {
|
||||
@ -1474,12 +1475,12 @@ var Random = (function() {
|
||||
}
|
||||
// See http://en.wikipedia.org/wiki/Marsaglia_polar_method
|
||||
while (true) {
|
||||
var x = (2 * rand()) - 1;
|
||||
var y = (2 * rand()) - 1;
|
||||
var s = (x * x) + (y * y);
|
||||
let x = (2 * rand()) - 1;
|
||||
let y = (2 * rand()) - 1;
|
||||
let s = (x * x) + (y * y);
|
||||
|
||||
if (s > 0 && s < 1) {
|
||||
var standardNormal = x * Math.sqrt(-2 * Math.log(s) / s);
|
||||
let standardNormal = x * Math.sqrt(-2 * Math.log(s) / s);
|
||||
return mean + (standardDeviation * standardNormal);
|
||||
}
|
||||
}
|
||||
@ -1519,19 +1520,19 @@ function timestampCmp(ts1, ts2) {
|
||||
|
||||
let Geo = {};
|
||||
Geo.distance = function(a, b) {
|
||||
var ax = null;
|
||||
var ay = null;
|
||||
var bx = null;
|
||||
var by = null;
|
||||
let ax = null;
|
||||
let ay = null;
|
||||
let bx = null;
|
||||
let by = null;
|
||||
|
||||
for (var key in a) {
|
||||
for (let key in a) {
|
||||
if (ax == null)
|
||||
ax = a[key];
|
||||
else if (ay == null)
|
||||
ay = a[key];
|
||||
}
|
||||
|
||||
for (var key in b) {
|
||||
for (let key in b) {
|
||||
if (bx == null)
|
||||
bx = b[key];
|
||||
else if (by == null)
|
||||
@ -1542,32 +1543,32 @@ Geo.distance = function(a, b) {
|
||||
};
|
||||
|
||||
Geo.sphereDistance = function(a, b) {
|
||||
var ax = null;
|
||||
var ay = null;
|
||||
var bx = null;
|
||||
var by = null;
|
||||
let ax = null;
|
||||
let ay = null;
|
||||
let bx = null;
|
||||
let by = null;
|
||||
|
||||
// TODO swap order of x and y when done on server
|
||||
for (var key in a) {
|
||||
for (let key in a) {
|
||||
if (ax == null)
|
||||
ax = a[key] * (Math.PI / 180);
|
||||
else if (ay == null)
|
||||
ay = a[key] * (Math.PI / 180);
|
||||
}
|
||||
|
||||
for (var key in b) {
|
||||
for (let key in b) {
|
||||
if (bx == null)
|
||||
bx = b[key] * (Math.PI / 180);
|
||||
else if (by == null)
|
||||
by = b[key] * (Math.PI / 180);
|
||||
}
|
||||
|
||||
var sin_x1 = Math.sin(ax), cos_x1 = Math.cos(ax);
|
||||
var sin_y1 = Math.sin(ay), cos_y1 = Math.cos(ay);
|
||||
var sin_x2 = Math.sin(bx), cos_x2 = Math.cos(bx);
|
||||
var sin_y2 = Math.sin(by), cos_y2 = Math.cos(by);
|
||||
let sin_x1 = Math.sin(ax), cos_x1 = Math.cos(ax);
|
||||
let sin_y1 = Math.sin(ay), cos_y1 = Math.cos(ay);
|
||||
let sin_x2 = Math.sin(bx), cos_x2 = Math.cos(bx);
|
||||
let sin_y2 = Math.sin(by), cos_y2 = Math.cos(by);
|
||||
|
||||
var cross_prod = (cos_y1 * cos_x1 * cos_y2 * cos_x2) + (cos_y1 * sin_x1 * cos_y2 * sin_x2) +
|
||||
let cross_prod = (cos_y1 * cos_x1 * cos_y2 * cos_x2) + (cos_y1 * sin_x1 * cos_y2 * sin_x2) +
|
||||
(sin_y1 * sin_y2);
|
||||
|
||||
if (cross_prod >= 1 || cross_prod <= -1) {
|
||||
@ -1600,23 +1601,23 @@ function _awaitRSHostViaRSMonitor(hostAddr, desiredState, rsName, timeout) {
|
||||
print("Awaiting " + hostAddr + " to be " + tojson(desiredState) + " in " +
|
||||
" rs " + rsName);
|
||||
|
||||
var tests = 0;
|
||||
let tests = 0;
|
||||
assert.soon(
|
||||
function() {
|
||||
var stats = _replMonitorStats(rsName);
|
||||
let stats = _replMonitorStats(rsName);
|
||||
if (tests++ % 10 == 0) {
|
||||
printjson(stats);
|
||||
}
|
||||
|
||||
for (var i = 0; i < stats.length; i++) {
|
||||
var node = stats[i];
|
||||
for (let i = 0; i < stats.length; i++) {
|
||||
let node = stats[i];
|
||||
printjson(node);
|
||||
if (node["addr"] !== hostAddr)
|
||||
continue;
|
||||
|
||||
// Check that *all* hostAddr properties match desiredState properties
|
||||
var stateReached = true;
|
||||
for (var prop in desiredState) {
|
||||
let stateReached = true;
|
||||
for (let prop in desiredState) {
|
||||
if (isObject(desiredState[prop])) {
|
||||
if (!friendlyEqual(sortDoc(desiredState[prop]), sortDoc(node[prop]))) {
|
||||
stateReached = false;
|
||||
@ -1717,7 +1718,7 @@ rs.printReplicationInfo = function() {
|
||||
};
|
||||
rs._runCmd = function(c) {
|
||||
// after the command, catch the disconnect and reconnect if necessary
|
||||
var res = null;
|
||||
let res = null;
|
||||
try {
|
||||
res = globalThis.db.adminCommand(c);
|
||||
} catch (e) {
|
||||
@ -1798,18 +1799,18 @@ rs.add = function(hostport, arb) {
|
||||
let self = this;
|
||||
|
||||
assert.soon(function() {
|
||||
var cfg = hostport;
|
||||
let cfg = hostport;
|
||||
|
||||
var local = globalThis.db.getSiblingDB("local");
|
||||
let local = globalThis.db.getSiblingDB("local");
|
||||
assert(local.system.replset.count() <= 1,
|
||||
"error: local.system.replset has unexpected contents");
|
||||
var c = local.system.replset.findOne();
|
||||
let c = local.system.replset.findOne();
|
||||
assert(c, "no config object retrievable from local.system.replset");
|
||||
|
||||
const attemptedVersion = c.version++;
|
||||
|
||||
var max = 0;
|
||||
for (var i in c.members) {
|
||||
let max = 0;
|
||||
for (let i in c.members) {
|
||||
// Omit 'newlyAdded' field if it exists in the config.
|
||||
delete c.members[i].newlyAdded;
|
||||
if (c.members[i]._id > max)
|
||||
@ -1859,7 +1860,7 @@ rs.syncFrom = function(host) {
|
||||
return globalThis.db._adminCommand({replSetSyncFrom: host});
|
||||
};
|
||||
rs.stepDown = function(stepdownSecs, catchUpSecs) {
|
||||
var cmdObj = {replSetStepDown: stepdownSecs === undefined ? 60 : stepdownSecs};
|
||||
let cmdObj = {replSetStepDown: stepdownSecs === undefined ? 60 : stepdownSecs};
|
||||
if (catchUpSecs !== undefined) {
|
||||
cmdObj['secondaryCatchUpPeriodSecs'] = catchUpSecs;
|
||||
}
|
||||
@ -1873,7 +1874,7 @@ rs.addArb = function(hn) {
|
||||
};
|
||||
|
||||
rs.conf = function() {
|
||||
var resp = globalThis.db._adminCommand({replSetGetConfig: 1});
|
||||
let resp = globalThis.db._adminCommand({replSetGetConfig: 1});
|
||||
if (resp.ok && !(resp.errmsg) && resp.config)
|
||||
return resp.config;
|
||||
else if (resp.errmsg && resp.errmsg.startsWith("no such cmd"))
|
||||
@ -1883,14 +1884,14 @@ rs.conf = function() {
|
||||
rs.config = rs.conf;
|
||||
|
||||
rs.remove = function(hn) {
|
||||
var local = globalThis.db.getSiblingDB("local");
|
||||
let local = globalThis.db.getSiblingDB("local");
|
||||
assert(local.system.replset.count() <= 1,
|
||||
"error: local.system.replset has unexpected contents");
|
||||
var c = local.system.replset.findOne();
|
||||
let c = local.system.replset.findOne();
|
||||
assert(c, "no config object retrievable from local.system.replset");
|
||||
c.version++;
|
||||
|
||||
for (var i in c.members) {
|
||||
for (let i in c.members) {
|
||||
if (c.members[i].host == hn) {
|
||||
c.members.splice(i, 1);
|
||||
return globalThis.db._adminCommand({replSetReconfig: c});
|
||||
@ -1903,12 +1904,12 @@ rs.remove = function(hn) {
|
||||
rs.debug = {};
|
||||
|
||||
rs.debug.nullLastOpWritten = function(primary, secondary) {
|
||||
var p = connect(primary + "/local");
|
||||
var s = connect(secondary + "/local");
|
||||
let p = connect(primary + "/local");
|
||||
let s = connect(secondary + "/local");
|
||||
s.getMongo().setSecondaryOk();
|
||||
|
||||
var secondToLast = s.oplog.rs.find().sort({$natural: -1}).limit(1).next();
|
||||
var last = p.runCommand({
|
||||
let secondToLast = s.oplog.rs.find().sort({$natural: -1}).limit(1).next();
|
||||
let last = p.runCommand({
|
||||
findAndModify: "oplog.rs",
|
||||
query: {ts: {$gt: secondToLast.ts}},
|
||||
sort: {$natural: 1},
|
||||
@ -1926,7 +1927,7 @@ rs.debug.nullLastOpWritten = function(primary, secondary) {
|
||||
};
|
||||
|
||||
rs.debug.getLastOpWritten = function(server) {
|
||||
var s = globalThis.db.getSiblingDB("local");
|
||||
let s = globalThis.db.getSiblingDB("local");
|
||||
if (server) {
|
||||
s = connect(server + "/local");
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
var authutil;
|
||||
let authutil;
|
||||
|
||||
assert(!authutil);
|
||||
authutil = {};
|
||||
@ -7,12 +7,12 @@ authutil = {};
|
||||
* Logs out all connections "conn" from database "dbname".
|
||||
*/
|
||||
authutil.logout = function(conn, dbname) {
|
||||
var i;
|
||||
let i;
|
||||
if (null == conn.length) {
|
||||
conn = [conn];
|
||||
}
|
||||
for (i = 0; i < conn.length; ++i) {
|
||||
var curDB = new DB(conn[i], dbname);
|
||||
let curDB = new DB(conn[i], dbname);
|
||||
curDB.logout();
|
||||
}
|
||||
};
|
||||
@ -24,7 +24,7 @@ authutil.logout = function(conn, dbname) {
|
||||
* in "conns" in the logged-out-of-dbName state.
|
||||
*/
|
||||
authutil.assertAuthenticate = function(conns, dbName, authParams) {
|
||||
var conn, i, ex, ex2;
|
||||
let conn, i, ex, ex2;
|
||||
if (conns.length == null)
|
||||
conns = [conns];
|
||||
|
||||
@ -55,7 +55,7 @@ authutil.assertAuthenticate = function(conns, dbName, authParams) {
|
||||
* Raises in exception if any of the authentications succeed.
|
||||
*/
|
||||
authutil.assertAuthenticateFails = function(conns, dbName, authParams) {
|
||||
var conn, i;
|
||||
let conn, i;
|
||||
if (conns.length == null)
|
||||
conns = [conns];
|
||||
|
||||
@ -78,7 +78,7 @@ authutil.assertAuthenticateFails = function(conns, dbName, authParams) {
|
||||
* user.
|
||||
*/
|
||||
authutil.asCluster = function(conn, keyfile, action) {
|
||||
var ex;
|
||||
let ex;
|
||||
|
||||
// put a connection in an array for uniform processing.
|
||||
let connArray = conn;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/* global ShardingTest */
|
||||
|
||||
var sh = function() {
|
||||
let sh = function() {
|
||||
return "try sh.help();";
|
||||
};
|
||||
|
||||
@ -10,7 +10,7 @@ sh._checkMongos = function() {
|
||||
// config shard which returns mongod hello responses (i.e. do not have "isdbgrid").
|
||||
return;
|
||||
}
|
||||
var x = globalThis.db._helloOrLegacyHello();
|
||||
let x = globalThis.db._helloOrLegacyHello();
|
||||
if (x.msg != "isdbgrid") {
|
||||
throw Error("not connected to a mongos");
|
||||
}
|
||||
@ -167,7 +167,7 @@ sh.addShard = function(url) {
|
||||
|
||||
sh.enableSharding = function(dbname, shardName) {
|
||||
assert(dbname, "need a valid dbname");
|
||||
var command = {enableSharding: dbname};
|
||||
let command = {enableSharding: dbname};
|
||||
if (shardName) {
|
||||
command.primaryShard = shardName;
|
||||
}
|
||||
@ -179,7 +179,7 @@ sh.shardCollection = function(fullName, key, unique, options) {
|
||||
assert(key, "need a key");
|
||||
assert(typeof (key) == "object", "key needs to be an object");
|
||||
|
||||
var cmd = {shardCollection: fullName, key: key};
|
||||
let cmd = {shardCollection: fullName, key: key};
|
||||
if (unique)
|
||||
cmd.unique = true;
|
||||
if (options) {
|
||||
@ -232,21 +232,21 @@ sh.isBalancerRunning = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = sh._getConfigDB();
|
||||
|
||||
var result = configDB.adminCommand({balancerStatus: 1});
|
||||
let result = configDB.adminCommand({balancerStatus: 1});
|
||||
return assert.commandWorked(result).inBalancerRound;
|
||||
};
|
||||
|
||||
sh.stopBalancer = function(timeoutMs, interval) {
|
||||
timeoutMs = timeoutMs || 60000;
|
||||
|
||||
var result = globalThis.db.adminCommand({balancerStop: 1, maxTimeMS: timeoutMs});
|
||||
let result = globalThis.db.adminCommand({balancerStop: 1, maxTimeMS: timeoutMs});
|
||||
return assert.commandWorked(result);
|
||||
};
|
||||
|
||||
sh.startBalancer = function(timeoutMs, interval) {
|
||||
timeoutMs = timeoutMs || 60000;
|
||||
|
||||
var result = globalThis.db.adminCommand({balancerStart: 1, maxTimeMS: timeoutMs});
|
||||
let result = globalThis.db.adminCommand({balancerStart: 1, maxTimeMS: timeoutMs});
|
||||
return assert.commandWorked(result);
|
||||
};
|
||||
|
||||
@ -279,7 +279,7 @@ sh.stopAutoMerger = function(configDB) {
|
||||
sh.shouldAutoMerge = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = sh._getConfigDB();
|
||||
var automerge = configDB.settings.findOne({_id: 'automerge'});
|
||||
let automerge = configDB.settings.findOne({_id: 'automerge'});
|
||||
if (automerge == null) {
|
||||
return true;
|
||||
}
|
||||
@ -290,7 +290,7 @@ sh.disableAutoMerger = function(coll) {
|
||||
if (coll === undefined) {
|
||||
throw Error("Must specify collection");
|
||||
}
|
||||
var dbase = globalThis.db;
|
||||
let dbase = globalThis.db;
|
||||
if (coll instanceof DBCollection) {
|
||||
dbase = coll.getDB();
|
||||
} else {
|
||||
@ -304,7 +304,7 @@ sh.enableAutoMerger = function(coll) {
|
||||
if (coll === undefined) {
|
||||
throw Error("Must specify collection");
|
||||
}
|
||||
var dbase = globalThis.db;
|
||||
let dbase = globalThis.db;
|
||||
if (coll instanceof DBCollection) {
|
||||
dbase = coll.getDB();
|
||||
} else {
|
||||
@ -315,8 +315,8 @@ sh.enableAutoMerger = function(coll) {
|
||||
};
|
||||
|
||||
sh.waitForPingChange = function(activePings, timeout, interval) {
|
||||
var isPingChanged = function(activePing) {
|
||||
var newPing = sh._getConfigDB().mongos.findOne({_id: activePing._id});
|
||||
let isPingChanged = function(activePing) {
|
||||
let newPing = sh._getConfigDB().mongos.findOne({_id: activePing._id});
|
||||
return !newPing || newPing.ping + "" != activePing.ping + "";
|
||||
};
|
||||
|
||||
@ -324,17 +324,17 @@ sh.waitForPingChange = function(activePings, timeout, interval) {
|
||||
// happened
|
||||
|
||||
// Timeout all pings on the same clock
|
||||
var start = new Date();
|
||||
let start = new Date();
|
||||
|
||||
var remainingPings = [];
|
||||
for (var i = 0; i < activePings.length; i++) {
|
||||
var activePing = activePings[i];
|
||||
let remainingPings = [];
|
||||
for (let i = 0; i < activePings.length; i++) {
|
||||
let activePing = activePings[i];
|
||||
print("Waiting for active host " + activePing._id +
|
||||
" to recognize new settings... (ping : " + activePing.ping + ")");
|
||||
|
||||
// Do a manual timeout here, avoid scary assert.soon errors
|
||||
var timeout = timeout || 30000;
|
||||
var interval = interval || 200;
|
||||
timeout ||= 30000;
|
||||
interval ||= 200;
|
||||
while (isPingChanged(activePing) != true) {
|
||||
if ((new Date()).getTime() - start.getTime() > timeout) {
|
||||
print("Waited for active ping to change for host " + activePing._id +
|
||||
@ -356,8 +356,8 @@ sh.waitForPingChange = function(activePings, timeout, interval) {
|
||||
sh.awaitBalancerRound = function(timeout, interval) {
|
||||
timeout = timeout || 60000;
|
||||
|
||||
var initialStatus = sh._getBalancerStatus();
|
||||
var currentStatus;
|
||||
let initialStatus = sh._getBalancerStatus();
|
||||
let currentStatus;
|
||||
assert.soon(function() {
|
||||
currentStatus = sh._getBalancerStatus();
|
||||
assert.eq(currentStatus.mode, 'full', "Balancer is disabled");
|
||||
@ -408,7 +408,7 @@ sh.awaitCollectionBalance = function(coll, timeout, interval) {
|
||||
{'$group': {'_id': null, 'totalNumOrphanDocs': {'$sum': '$storageStats.numOrphanDocs'}}}
|
||||
];
|
||||
|
||||
var oldDb = (typeof (globalThis.db) === 'undefined' ? undefined : globalThis.db);
|
||||
let oldDb = (typeof (globalThis.db) === 'undefined' ? undefined : globalThis.db);
|
||||
try {
|
||||
globalThis.db = coll.getDB();
|
||||
|
||||
@ -454,7 +454,7 @@ sh.verifyCollectionIsBalanced = function(coll) {
|
||||
throw Error("Must specify collection");
|
||||
}
|
||||
|
||||
var oldDb = globalThis.db;
|
||||
let oldDb = globalThis.db;
|
||||
try {
|
||||
globalThis.db = coll.getDB();
|
||||
|
||||
@ -507,9 +507,9 @@ sh.verifyCollectionIsBalanced = function(coll) {
|
||||
* mongos )
|
||||
*/
|
||||
sh._lastMigration = function(ns) {
|
||||
var coll = null;
|
||||
var dbase = null;
|
||||
var config = null;
|
||||
let coll = null;
|
||||
let dbase = null;
|
||||
let config = null;
|
||||
|
||||
if (!ns) {
|
||||
config = globalThis.db.getSiblingDB("config");
|
||||
@ -535,13 +535,13 @@ sh._lastMigration = function(ns) {
|
||||
}
|
||||
}
|
||||
|
||||
var searchDoc = {what: /^moveChunk/};
|
||||
let searchDoc = {what: /^moveChunk/};
|
||||
if (coll)
|
||||
searchDoc.ns = coll + "";
|
||||
if (dbase)
|
||||
searchDoc.ns = new RegExp("^" + dbase + "\\.");
|
||||
|
||||
var cursor = config.changelog.find(searchDoc).sort({time: -1}).limit(1);
|
||||
let cursor = config.changelog.find(searchDoc).sort({time: -1}).limit(1);
|
||||
if (cursor.hasNext())
|
||||
return cursor.next();
|
||||
else
|
||||
@ -549,12 +549,12 @@ sh._lastMigration = function(ns) {
|
||||
};
|
||||
|
||||
sh.addShardTag = function(shard, tag) {
|
||||
var result = sh.addShardToZone(shard, tag);
|
||||
let result = sh.addShardToZone(shard, tag);
|
||||
if (result.code != ErrorCodes.CommandNotFound) {
|
||||
return result;
|
||||
}
|
||||
|
||||
var config = sh._getConfigDB();
|
||||
let config = sh._getConfigDB();
|
||||
if (config.shards.findOne({_id: shard}) == null) {
|
||||
throw Error("can't find a shard with name: " + shard);
|
||||
}
|
||||
@ -563,12 +563,12 @@ sh.addShardTag = function(shard, tag) {
|
||||
};
|
||||
|
||||
sh.removeShardTag = function(shard, tag) {
|
||||
var result = sh.removeShardFromZone(shard, tag);
|
||||
let result = sh.removeShardFromZone(shard, tag);
|
||||
if (result.code != ErrorCodes.CommandNotFound) {
|
||||
return result;
|
||||
}
|
||||
|
||||
var config = sh._getConfigDB();
|
||||
let config = sh._getConfigDB();
|
||||
if (config.shards.findOne({_id: shard}) == null) {
|
||||
throw Error("can't find a shard with name: " + shard);
|
||||
}
|
||||
@ -577,7 +577,7 @@ sh.removeShardTag = function(shard, tag) {
|
||||
};
|
||||
|
||||
sh.addTagRange = function(ns, min, max, tag) {
|
||||
var result = sh.updateZoneKeyRange(ns, min, max, tag);
|
||||
let result = sh.updateZoneKeyRange(ns, min, max, tag);
|
||||
if (result.code != ErrorCodes.CommandNotFound) {
|
||||
return result;
|
||||
}
|
||||
@ -586,7 +586,7 @@ sh.addTagRange = function(ns, min, max, tag) {
|
||||
throw new Error("min and max cannot be the same");
|
||||
}
|
||||
|
||||
var config = sh._getConfigDB();
|
||||
let config = sh._getConfigDB();
|
||||
return assert.commandWorked(
|
||||
config.tags.update({_id: {ns: ns, min: min}},
|
||||
{_id: {ns: ns, min: min}, ns: ns, min: min, max: max, tag: tag},
|
||||
@ -617,7 +617,7 @@ sh.removeRangeFromZone = function(ns, min, max) {
|
||||
sh.getBalancerWindow = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = globalThis.db.getSiblingDB('config');
|
||||
var settings = configDB.settings.findOne({_id: 'balancer'});
|
||||
let settings = configDB.settings.findOne({_id: 'balancer'});
|
||||
if (settings == null) {
|
||||
return null;
|
||||
}
|
||||
@ -630,8 +630,8 @@ sh.getBalancerWindow = function(configDB) {
|
||||
sh.getActiveMigrations = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = globalThis.db.getSiblingDB('config');
|
||||
var activeLocks = configDB.locks.find({state: {$eq: 2}});
|
||||
var result = [];
|
||||
let activeLocks = configDB.locks.find({state: {$eq: 2}});
|
||||
let result = [];
|
||||
if (activeLocks != null) {
|
||||
activeLocks.forEach(function(lock) {
|
||||
result.push({_id: lock._id, when: lock.when});
|
||||
@ -643,8 +643,8 @@ sh.getActiveMigrations = function(configDB) {
|
||||
sh.getRecentFailedRounds = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = globalThis.db.getSiblingDB('config');
|
||||
var balErrs = configDB.actionlog.find({what: "balancer.round"}).sort({time: -1}).limit(5);
|
||||
var result = {count: 0, lastErr: "", lastTime: " "};
|
||||
let balErrs = configDB.actionlog.find({what: "balancer.round"}).sort({time: -1}).limit(5);
|
||||
let result = {count: 0, lastErr: "", lastTime: " "};
|
||||
if (balErrs != null) {
|
||||
balErrs.forEach(function(r) {
|
||||
if (r.details.errorOccurred) {
|
||||
@ -667,10 +667,10 @@ sh.getRecentFailedRounds = function(configDB) {
|
||||
sh.getRecentMigrations = function(configDB) {
|
||||
if (configDB === undefined)
|
||||
configDB = sh._getConfigDB();
|
||||
var yesterday = new Date(new Date() - 24 * 60 * 60 * 1000);
|
||||
let yesterday = new Date(new Date() - 24 * 60 * 60 * 1000);
|
||||
|
||||
// Successful migrations.
|
||||
var result = configDB.changelog
|
||||
let result = configDB.changelog
|
||||
.aggregate([
|
||||
{
|
||||
$match: {
|
||||
@ -750,15 +750,15 @@ function printShardingStatus(configDB, verbose) {
|
||||
configDB = globalThis.db.getSiblingDB('config');
|
||||
}
|
||||
|
||||
var version = configDB.getCollection("version").findOne();
|
||||
let version = configDB.getCollection("version").findOne();
|
||||
if (version == null) {
|
||||
print(
|
||||
"printShardingStatus: this db does not have sharding enabled. be sure you are connecting to a mongos from the shell and not to a mongod.");
|
||||
return;
|
||||
}
|
||||
|
||||
var raw = "";
|
||||
var output = function(indent, s) {
|
||||
let raw = "";
|
||||
let output = function(indent, s) {
|
||||
raw += sh._shardingStatusStr(indent, s);
|
||||
};
|
||||
output(0, "--- Sharding Status --- ");
|
||||
@ -770,10 +770,10 @@ function printShardingStatus(configDB, verbose) {
|
||||
});
|
||||
|
||||
// (most recently) active mongoses
|
||||
var mongosActiveThresholdMs = 60000;
|
||||
var mostRecentMongos = configDB.mongos.find().sort({ping: -1}).limit(1);
|
||||
var mostRecentMongosTime = null;
|
||||
var mongosAdjective = "most recently active";
|
||||
let mongosActiveThresholdMs = 60000;
|
||||
let mostRecentMongos = configDB.mongos.find().sort({ping: -1}).limit(1);
|
||||
let mostRecentMongosTime = null;
|
||||
let mongosAdjective = "most recently active";
|
||||
if (mostRecentMongos.hasNext()) {
|
||||
mostRecentMongosTime = mostRecentMongos.next().ping;
|
||||
// Mongoses older than the threshold are the most recent, but cannot be
|
||||
@ -788,10 +788,10 @@ function printShardingStatus(configDB, verbose) {
|
||||
if (mostRecentMongosTime === null) {
|
||||
output(2, "none");
|
||||
} else {
|
||||
var recentMongosQuery = {
|
||||
let recentMongosQuery = {
|
||||
ping: {
|
||||
$gt: (function() {
|
||||
var d = mostRecentMongosTime;
|
||||
let d = mostRecentMongosTime;
|
||||
d.setTime(d.getTime() - mongosActiveThresholdMs);
|
||||
return d;
|
||||
})()
|
||||
@ -845,7 +845,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
output(2, "Currently running: " + (balancerRunning ? "yes" : "no"));
|
||||
|
||||
// Output the balancer window
|
||||
var balSettings = sh.getBalancerWindow(configDB);
|
||||
let balSettings = sh.getBalancerWindow(configDB);
|
||||
if (balSettings) {
|
||||
output(3,
|
||||
"Balancer active window is set between " + balSettings.start + " and " +
|
||||
@ -853,7 +853,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
}
|
||||
|
||||
// Output the list of active migrations
|
||||
var activeMigrations = sh.getActiveMigrations(configDB);
|
||||
let activeMigrations = sh.getActiveMigrations(configDB);
|
||||
if (activeMigrations.length > 0) {
|
||||
output(2, "Collections with active migrations: ");
|
||||
activeMigrations.forEach(function(migration) {
|
||||
@ -862,13 +862,13 @@ function printShardingStatus(configDB, verbose) {
|
||||
}
|
||||
|
||||
// Actionlog and version checking only works on 2.7 and greater
|
||||
var versionHasActionlog = false;
|
||||
var metaDataVersion = configDB.getCollection("version").findOne().currentVersion;
|
||||
let versionHasActionlog = false;
|
||||
let metaDataVersion = configDB.getCollection("version").findOne().currentVersion;
|
||||
if (metaDataVersion > 5) {
|
||||
versionHasActionlog = true;
|
||||
}
|
||||
if (metaDataVersion == 5) {
|
||||
var verArray = globalThis.db.getServerBuildInfo().rawData().versionArray;
|
||||
let verArray = globalThis.db.getServerBuildInfo().rawData().versionArray;
|
||||
if (verArray[0] == 2 && verArray[1] > 6) {
|
||||
versionHasActionlog = true;
|
||||
}
|
||||
@ -876,7 +876,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
|
||||
if (versionHasActionlog) {
|
||||
// Review config.actionlog for errors
|
||||
var actionReport = sh.getRecentFailedRounds(configDB);
|
||||
let actionReport = sh.getRecentFailedRounds(configDB);
|
||||
// Always print the number of failed rounds
|
||||
output(2, "Failed balancer rounds in last 5 attempts: " + actionReport.count);
|
||||
|
||||
@ -887,7 +887,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
}
|
||||
|
||||
output(2, "Migration results for the last 24 hours: ");
|
||||
var migrations = sh.getRecentMigrations(configDB);
|
||||
let migrations = sh.getRecentMigrations(configDB);
|
||||
if (migrations.length > 0) {
|
||||
migrations.forEach(function(x) {
|
||||
if (x._id === "Success") {
|
||||
@ -905,7 +905,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
|
||||
output(1, "databases:");
|
||||
|
||||
var databases = configDB.databases.find().sort({name: 1}).toArray();
|
||||
let databases = configDB.databases.find().sort({name: 1}).toArray();
|
||||
|
||||
// Special case the config db, since it doesn't have a record in config.databases.
|
||||
databases.push({"_id": "config", "primary": "config", "partitioned": true});
|
||||
@ -914,14 +914,14 @@ function printShardingStatus(configDB, verbose) {
|
||||
});
|
||||
|
||||
databases.forEach(function(db) {
|
||||
var truthy = function(value) {
|
||||
let truthy = function(value) {
|
||||
return !!value;
|
||||
};
|
||||
var nonBooleanNote = function(name, value) {
|
||||
let nonBooleanNote = function(name, value) {
|
||||
// If the given value is not a boolean, return a string of the
|
||||
// form " (<name>: <value>)", where <value> is converted to JSON.
|
||||
var t = typeof (value);
|
||||
var s = "";
|
||||
let t = typeof (value);
|
||||
let s = "";
|
||||
if (t != "boolean" && t != "undefined") {
|
||||
s = " (" + name + ": " + tojson(value) + ")";
|
||||
}
|
||||
@ -956,7 +956,7 @@ function printShardingStatus(configDB, verbose) {
|
||||
{$sort: {shard: 1}})
|
||||
.toArray();
|
||||
|
||||
var totalChunks = 0;
|
||||
let totalChunks = 0;
|
||||
res.forEach(function(z) {
|
||||
totalChunks += z.nChunks;
|
||||
output(5, z.shard + "\t" + z.nChunks);
|
||||
@ -995,14 +995,14 @@ function printShardingSizes(configDB) {
|
||||
configDB = globalThis.db.getSiblingDB('config');
|
||||
}
|
||||
|
||||
var version = configDB.getCollection("version").findOne();
|
||||
let version = configDB.getCollection("version").findOne();
|
||||
if (version == null) {
|
||||
print("printShardingSizes : not a shard db!");
|
||||
return;
|
||||
}
|
||||
|
||||
var raw = "";
|
||||
var output = function(indent, s) {
|
||||
let raw = "";
|
||||
let output = function(indent, s) {
|
||||
raw += sh._shardingStatusStr(indent, s);
|
||||
};
|
||||
output(0, "--- Sharding Sizes --- ");
|
||||
@ -1013,7 +1013,7 @@ function printShardingSizes(configDB) {
|
||||
output(2, tojson(z));
|
||||
});
|
||||
|
||||
var saveDB = globalThis.db;
|
||||
let saveDB = globalThis.db;
|
||||
output(1, "databases:");
|
||||
configDB.databases.find().sort({name: 1}).forEach(function(db) {
|
||||
output(2, tojson(db, "", true));
|
||||
@ -1023,7 +1023,7 @@ function printShardingSizes(configDB) {
|
||||
.forEach(function(coll) {
|
||||
output(3, coll._id + " chunks:");
|
||||
configDB.chunks.find({"ns": coll._id}).sort({min: 1}).forEach(function(chunk) {
|
||||
var out = saveDB.adminCommand(
|
||||
let out = saveDB.adminCommand(
|
||||
{dataSize: coll._id, keyPattern: coll.key, min: chunk.min, max: chunk.max});
|
||||
delete out.millis;
|
||||
delete out.ok;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user