common.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. 'use strict';
  2. const Long = require('../core').BSON.Long;
  3. const MongoError = require('../core').MongoError;
  4. const ObjectID = require('../core').BSON.ObjectID;
  5. const BSON = require('../core').BSON;
  6. const MongoWriteConcernError = require('../core').MongoWriteConcernError;
  7. const emitWarningOnce = require('../utils').emitWarningOnce;
  8. const toError = require('../utils').toError;
  9. const handleCallback = require('../utils').handleCallback;
  10. const applyRetryableWrites = require('../utils').applyRetryableWrites;
  11. const applyWriteConcern = require('../utils').applyWriteConcern;
  12. const executeLegacyOperation = require('../utils').executeLegacyOperation;
  13. const isPromiseLike = require('../utils').isPromiseLike;
  14. const hasAtomicOperators = require('../utils').hasAtomicOperators;
  15. const maxWireVersion = require('../core/utils').maxWireVersion;
  16. // Error codes
  17. const WRITE_CONCERN_ERROR = 64;
  18. // Insert types
  19. const INSERT = 1;
  20. const UPDATE = 2;
  21. const REMOVE = 3;
  22. const bson = new BSON([
  23. BSON.Binary,
  24. BSON.Code,
  25. BSON.DBRef,
  26. BSON.Decimal128,
  27. BSON.Double,
  28. BSON.Int32,
  29. BSON.Long,
  30. BSON.Map,
  31. BSON.MaxKey,
  32. BSON.MinKey,
  33. BSON.ObjectId,
  34. BSON.BSONRegExp,
  35. BSON.Symbol,
  36. BSON.Timestamp
  37. ]);
  38. /**
  39. * Keeps the state of a unordered batch so we can rewrite the results
  40. * correctly after command execution
  41. * @ignore
  42. */
  43. class Batch {
  44. constructor(batchType, originalZeroIndex) {
  45. this.originalZeroIndex = originalZeroIndex;
  46. this.currentIndex = 0;
  47. this.originalIndexes = [];
  48. this.batchType = batchType;
  49. this.operations = [];
  50. this.size = 0;
  51. this.sizeBytes = 0;
  52. }
  53. }
  54. const kUpsertedIds = Symbol('upsertedIds');
  55. const kInsertedIds = Symbol('insertedIds');
  56. /**
  57. * @classdesc
  58. * The result of a bulk write.
  59. */
  60. class BulkWriteResult {
  61. /**
  62. * Create a new BulkWriteResult instance
  63. *
  64. * **NOTE:** Internal Type, do not instantiate directly
  65. */
  66. constructor(bulkResult) {
  67. this.result = bulkResult;
  68. this[kUpsertedIds] = undefined;
  69. this[kInsertedIds] = undefined;
  70. }
  71. /** Number of documents inserted. */
  72. get insertedCount() {
  73. return typeof this.result.nInserted !== 'number' ? 0 : this.result.nInserted;
  74. }
  75. /** Number of documents matched for update. */
  76. get matchedCount() {
  77. return typeof this.result.nMatched !== 'number' ? 0 : this.result.nMatched;
  78. }
  79. /** Number of documents modified. */
  80. get modifiedCount() {
  81. return typeof this.result.nModified !== 'number' ? 0 : this.result.nModified;
  82. }
  83. /** Number of documents deleted. */
  84. get deletedCount() {
  85. return typeof this.result.nRemoved !== 'number' ? 0 : this.result.nRemoved;
  86. }
  87. /** Number of documents upserted. */
  88. get upsertedCount() {
  89. return !this.result.upserted ? 0 : this.result.upserted.length;
  90. }
  91. /** Upserted document generated Id's, hash key is the index of the originating operation */
  92. get upsertedIds() {
  93. if (this[kUpsertedIds]) {
  94. return this[kUpsertedIds];
  95. }
  96. this[kUpsertedIds] = {};
  97. for (const doc of this.result.upserted || []) {
  98. this[kUpsertedIds][doc.index] = doc._id;
  99. }
  100. return this[kUpsertedIds];
  101. }
  102. /** Inserted document generated Id's, hash key is the index of the originating operation */
  103. get insertedIds() {
  104. if (this[kInsertedIds]) {
  105. return this[kInsertedIds];
  106. }
  107. this[kInsertedIds] = {};
  108. for (const doc of this.result.insertedIds || []) {
  109. this[kInsertedIds][doc.index] = doc._id;
  110. }
  111. return this[kInsertedIds];
  112. }
  113. /** The number of inserted documents @type {number} */
  114. get n() {
  115. return this.result.insertedCount;
  116. }
  117. /**
  118. * Evaluates to true if the bulk operation correctly executes
  119. * @type {boolean}
  120. */
  121. get ok() {
  122. return this.result.ok;
  123. }
  124. /**
  125. * The number of inserted documents
  126. * @type {number}
  127. */
  128. get nInserted() {
  129. return this.result.nInserted;
  130. }
  131. /**
  132. * Number of upserted documents
  133. * @type {number}
  134. */
  135. get nUpserted() {
  136. return this.result.nUpserted;
  137. }
  138. /**
  139. * Number of matched documents
  140. * @type {number}
  141. */
  142. get nMatched() {
  143. return this.result.nMatched;
  144. }
  145. /**
  146. * Number of documents updated physically on disk
  147. * @type {number}
  148. */
  149. get nModified() {
  150. return this.result.nModified;
  151. }
  152. /**
  153. * Number of removed documents
  154. * @type {number}
  155. */
  156. get nRemoved() {
  157. return this.result.nRemoved;
  158. }
  159. /**
  160. * Returns an array of all inserted ids
  161. *
  162. * @return {object[]}
  163. */
  164. getInsertedIds() {
  165. return this.result.insertedIds;
  166. }
  167. /**
  168. * Returns an array of all upserted ids
  169. *
  170. * @return {object[]}
  171. */
  172. getUpsertedIds() {
  173. return this.result.upserted;
  174. }
  175. /**
  176. * Returns the upserted id at the given index
  177. *
  178. * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index
  179. * @return {object}
  180. */
  181. getUpsertedIdAt(index) {
  182. return this.result.upserted[index];
  183. }
  184. /**
  185. * Returns raw internal result
  186. *
  187. * @return {object}
  188. */
  189. getRawResponse() {
  190. return this.result;
  191. }
  192. /**
  193. * Returns true if the bulk operation contains a write error
  194. *
  195. * @return {boolean}
  196. */
  197. hasWriteErrors() {
  198. return this.result.writeErrors.length > 0;
  199. }
  200. /**
  201. * Returns the number of write errors off the bulk operation
  202. *
  203. * @return {number}
  204. */
  205. getWriteErrorCount() {
  206. return this.result.writeErrors.length;
  207. }
  208. /**
  209. * Returns a specific write error object
  210. *
  211. * @param {number} index of the write error to return, returns null if there is no result for passed in index
  212. * @return {WriteError}
  213. */
  214. getWriteErrorAt(index) {
  215. if (index < this.result.writeErrors.length) {
  216. return this.result.writeErrors[index];
  217. }
  218. return null;
  219. }
  220. /**
  221. * Retrieve all write errors
  222. *
  223. * @return {WriteError[]}
  224. */
  225. getWriteErrors() {
  226. return this.result.writeErrors;
  227. }
  228. /**
  229. * Retrieve lastOp if available
  230. *
  231. * @return {object}
  232. */
  233. getLastOp() {
  234. return this.result.lastOp;
  235. }
  236. /**
  237. * Retrieve the write concern error if any
  238. *
  239. * @return {WriteConcernError}
  240. */
  241. getWriteConcernError() {
  242. if (this.result.writeConcernErrors.length === 0) {
  243. return null;
  244. } else if (this.result.writeConcernErrors.length === 1) {
  245. // Return the error
  246. return this.result.writeConcernErrors[0];
  247. } else {
  248. // Combine the errors
  249. let errmsg = '';
  250. for (let i = 0; i < this.result.writeConcernErrors.length; i++) {
  251. const err = this.result.writeConcernErrors[i];
  252. errmsg = errmsg + err.errmsg;
  253. // TODO: Something better
  254. if (i === 0) errmsg = errmsg + ' and ';
  255. }
  256. return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR });
  257. }
  258. }
  259. /**
  260. * @return {object}
  261. */
  262. toJSON() {
  263. return this.result;
  264. }
  265. /**
  266. * @return {string}
  267. */
  268. toString() {
  269. return `BulkWriteResult(${this.toJSON(this.result)})`;
  270. }
  271. /**
  272. * @return {boolean}
  273. */
  274. isOk() {
  275. return this.result.ok === 1;
  276. }
  277. }
  278. /**
  279. * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation.
  280. */
  281. class WriteConcernError {
  282. /**
  283. * Create a new WriteConcernError instance
  284. *
  285. * **NOTE:** Internal Type, do not instantiate directly
  286. */
  287. constructor(err) {
  288. this.err = err;
  289. }
  290. /**
  291. * Write concern error code.
  292. * @type {number}
  293. */
  294. get code() {
  295. return this.err.code;
  296. }
  297. /**
  298. * Write concern error message.
  299. * @type {string}
  300. */
  301. get errmsg() {
  302. return this.err.errmsg;
  303. }
  304. /**
  305. * @return {object}
  306. */
  307. toJSON() {
  308. return { code: this.err.code, errmsg: this.err.errmsg };
  309. }
  310. /**
  311. * @return {string}
  312. */
  313. toString() {
  314. return `WriteConcernError(${this.err.errmsg})`;
  315. }
  316. }
  317. /**
  318. * @classdesc An error that occurred during a BulkWrite on the server.
  319. */
  320. class WriteError {
  321. /**
  322. * Create a new WriteError instance
  323. *
  324. * **NOTE:** Internal Type, do not instantiate directly
  325. */
  326. constructor(err) {
  327. this.err = err;
  328. }
  329. /**
  330. * WriteError code.
  331. * @type {number}
  332. */
  333. get code() {
  334. return this.err.code;
  335. }
  336. /**
  337. * WriteError original bulk operation index.
  338. * @type {number}
  339. */
  340. get index() {
  341. return this.err.index;
  342. }
  343. /**
  344. * WriteError message.
  345. * @type {string}
  346. */
  347. get errmsg() {
  348. return this.err.errmsg;
  349. }
  350. /**
  351. * Returns the underlying operation that caused the error
  352. * @return {object}
  353. */
  354. getOperation() {
  355. return this.err.op;
  356. }
  357. /**
  358. * @return {object}
  359. */
  360. toJSON() {
  361. return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
  362. }
  363. /**
  364. * @return {string}
  365. */
  366. toString() {
  367. return `WriteError(${JSON.stringify(this.toJSON())})`;
  368. }
  369. }
  370. /**
  371. * Converts the number to a Long or returns it.
  372. *
  373. * @ignore
  374. */
  375. function longOrConvert(value) {
  376. return typeof value === 'number' ? Long.fromNumber(value) : value;
  377. }
  378. /**
  379. * Merges results into shared data structure
  380. * @ignore
  381. */
  382. function mergeBatchResults(batch, bulkResult, err, result) {
  383. // If we have an error set the result to be the err object
  384. if (err) {
  385. result = err;
  386. } else if (result && result.result) {
  387. result = result.result;
  388. } else if (result == null) {
  389. return;
  390. }
  391. // Do we have a top level error stop processing and return
  392. if (result.ok === 0 && bulkResult.ok === 1) {
  393. bulkResult.ok = 0;
  394. const writeError = {
  395. index: 0,
  396. code: result.code || 0,
  397. errmsg: result.message,
  398. op: batch.operations[0]
  399. };
  400. bulkResult.writeErrors.push(new WriteError(writeError));
  401. return;
  402. } else if (result.ok === 0 && bulkResult.ok === 0) {
  403. return;
  404. }
  405. // The server write command specification states that lastOp is an optional
  406. // mongod only field that has a type of timestamp. Across various scarce specs
  407. // where opTime is mentioned, it is an "opaque" object that can have a "ts" and
  408. // "t" field with Timestamp and Long as their types respectively.
  409. // The "lastOp" field of the bulk write result is never mentioned in the driver
  410. // specifications or the bulk write spec, so we should probably just keep its
  411. // value consistent since it seems to vary.
  412. // See: https://github.com/mongodb/specifications/blob/master/source/driver-bulk-update.rst#results-object
  413. if (result.opTime || result.lastOp) {
  414. let opTime = result.lastOp || result.opTime;
  415. // If the opTime is a Timestamp, convert it to a consistent format to be
  416. // able to compare easily. Converting to the object from a timestamp is
  417. // much more straightforward than the other direction.
  418. if (opTime._bsontype === 'Timestamp') {
  419. opTime = { ts: opTime, t: Long.ZERO };
  420. }
  421. // If there's no lastOp, just set it.
  422. if (!bulkResult.lastOp) {
  423. bulkResult.lastOp = opTime;
  424. } else {
  425. // First compare the ts values and set if the opTimeTS value is greater.
  426. const lastOpTS = longOrConvert(bulkResult.lastOp.ts);
  427. const opTimeTS = longOrConvert(opTime.ts);
  428. if (opTimeTS.greaterThan(lastOpTS)) {
  429. bulkResult.lastOp = opTime;
  430. } else if (opTimeTS.equals(lastOpTS)) {
  431. // If the ts values are equal, then compare using the t values.
  432. const lastOpT = longOrConvert(bulkResult.lastOp.t);
  433. const opTimeT = longOrConvert(opTime.t);
  434. if (opTimeT.greaterThan(lastOpT)) {
  435. bulkResult.lastOp = opTime;
  436. }
  437. }
  438. }
  439. }
  440. // If we have an insert Batch type
  441. if (batch.batchType === INSERT && result.n) {
  442. bulkResult.nInserted = bulkResult.nInserted + result.n;
  443. }
  444. // If we have an insert Batch type
  445. if (batch.batchType === REMOVE && result.n) {
  446. bulkResult.nRemoved = bulkResult.nRemoved + result.n;
  447. }
  448. let nUpserted = 0;
  449. // We have an array of upserted values, we need to rewrite the indexes
  450. if (Array.isArray(result.upserted)) {
  451. nUpserted = result.upserted.length;
  452. for (let i = 0; i < result.upserted.length; i++) {
  453. bulkResult.upserted.push({
  454. index: result.upserted[i].index + batch.originalZeroIndex,
  455. _id: result.upserted[i]._id
  456. });
  457. }
  458. } else if (result.upserted) {
  459. nUpserted = 1;
  460. bulkResult.upserted.push({
  461. index: batch.originalZeroIndex,
  462. _id: result.upserted
  463. });
  464. }
  465. // If we have an update Batch type
  466. if (batch.batchType === UPDATE && result.n) {
  467. const nModified = result.nModified;
  468. bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
  469. bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
  470. if (typeof nModified === 'number') {
  471. bulkResult.nModified = bulkResult.nModified + nModified;
  472. } else {
  473. bulkResult.nModified = null;
  474. }
  475. }
  476. if (Array.isArray(result.writeErrors)) {
  477. for (let i = 0; i < result.writeErrors.length; i++) {
  478. const writeError = {
  479. index: batch.originalIndexes[result.writeErrors[i].index],
  480. code: result.writeErrors[i].code,
  481. errmsg: result.writeErrors[i].errmsg,
  482. op: batch.operations[result.writeErrors[i].index]
  483. };
  484. bulkResult.writeErrors.push(new WriteError(writeError));
  485. }
  486. }
  487. if (result.writeConcernError) {
  488. bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
  489. }
  490. }
  491. function executeCommands(bulkOperation, options, callback) {
  492. if (bulkOperation.s.batches.length === 0) {
  493. return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
  494. }
  495. const batch = bulkOperation.s.batches.shift();
  496. function resultHandler(err, result) {
  497. // Error is a driver related error not a bulk op error, terminate
  498. if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
  499. return handleCallback(callback, err);
  500. }
  501. // If we have and error
  502. if (err) err.ok = 0;
  503. if (err instanceof MongoWriteConcernError) {
  504. return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback);
  505. }
  506. // Merge the results together
  507. const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
  508. const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result);
  509. if (mergeResult != null) {
  510. return handleCallback(callback, null, writeResult);
  511. }
  512. if (bulkOperation.handleWriteError(callback, writeResult)) return;
  513. // Execute the next command in line
  514. executeCommands(bulkOperation, options, callback);
  515. }
  516. bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
  517. }
  518. /**
  519. * handles write concern error
  520. *
  521. * @ignore
  522. * @param {object} batch
  523. * @param {object} bulkResult
  524. * @param {boolean} ordered
  525. * @param {WriteConcernError} err
  526. * @param {function} callback
  527. */
  528. function handleMongoWriteConcernError(batch, bulkResult, err, callback) {
  529. mergeBatchResults(batch, bulkResult, null, err.result);
  530. const wrappedWriteConcernError = new WriteConcernError({
  531. errmsg: err.result.writeConcernError.errmsg,
  532. code: err.result.writeConcernError.result
  533. });
  534. return handleCallback(
  535. callback,
  536. new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
  537. null
  538. );
  539. }
  540. /**
  541. * @classdesc An error indicating an unsuccessful Bulk Write
  542. */
  543. class BulkWriteError extends MongoError {
  544. /**
  545. * Creates a new BulkWriteError
  546. *
  547. * @param {Error|string|object} message The error message
  548. * @param {BulkWriteResult} result The result of the bulk write operation
  549. * @extends {MongoError}
  550. */
  551. constructor(error, result) {
  552. const message = error.err || error.errmsg || error.errMessage || error;
  553. super(message);
  554. Object.assign(this, error);
  555. this.name = 'BulkWriteError';
  556. this.result = result;
  557. }
  558. /** Number of documents inserted. */
  559. get insertedCount() {
  560. return this.result.insertedCount;
  561. }
  562. /** Number of documents matched for update. */
  563. get matchedCount() {
  564. return this.result.matchedCount;
  565. }
  566. /** Number of documents modified. */
  567. get modifiedCount() {
  568. return this.result.modifiedCount;
  569. }
  570. /** Number of documents deleted. */
  571. get deletedCount() {
  572. return this.result.deletedCount;
  573. }
  574. /** Number of documents upserted. */
  575. get upsertedCount() {
  576. return this.result.upsertedCount;
  577. }
  578. /** Inserted document generated Id's, hash key is the index of the originating operation */
  579. get insertedIds() {
  580. return this.result.insertedIds;
  581. }
  582. /** Upserted document generated Id's, hash key is the index of the originating operation */
  583. get upsertedIds() {
  584. return this.result.upsertedIds;
  585. }
  586. }
  587. /**
  588. * @classdesc A builder object that is returned from {@link BulkOperationBase#find}.
  589. * Is used to build a write operation that involves a query filter.
  590. */
  591. class FindOperators {
  592. /**
  593. * Creates a new FindOperators object.
  594. *
  595. * **NOTE:** Internal Type, do not instantiate directly
  596. * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation
  597. */
  598. constructor(bulkOperation) {
  599. this.s = bulkOperation.s;
  600. }
  601. /**
  602. * Add a multiple update operation to the bulk operation
  603. *
  604. * @method
  605. * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}
  606. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  607. * @throws {MongoError} If operation cannot be added to bulk write
  608. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  609. */
  610. update(updateDocument) {
  611. // Perform upsert
  612. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  613. // Establish the update command
  614. const document = {
  615. q: this.s.currentOp.selector,
  616. u: updateDocument,
  617. multi: true,
  618. upsert: upsert
  619. };
  620. if (updateDocument.hint) {
  621. document.hint = updateDocument.hint;
  622. }
  623. // Clear out current Op
  624. this.s.currentOp = null;
  625. return this.s.options.addToOperationsList(this, UPDATE, document);
  626. }
  627. /**
  628. * Add a single update operation to the bulk operation
  629. *
  630. * @method
  631. * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}
  632. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  633. * @throws {MongoError} If operation cannot be added to bulk write
  634. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  635. */
  636. updateOne(updateDocument) {
  637. // Perform upsert
  638. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  639. // Establish the update command
  640. const document = {
  641. q: this.s.currentOp.selector,
  642. u: updateDocument,
  643. multi: false,
  644. upsert: upsert
  645. };
  646. if (updateDocument.hint) {
  647. document.hint = updateDocument.hint;
  648. }
  649. if (!hasAtomicOperators(updateDocument)) {
  650. throw new TypeError('Update document requires atomic operators');
  651. }
  652. // Clear out current Op
  653. this.s.currentOp = null;
  654. return this.s.options.addToOperationsList(this, UPDATE, document);
  655. }
  656. /**
  657. * Add a replace one operation to the bulk operation
  658. *
  659. * @method
  660. * @param {object} replacement the new document to replace the existing one with
  661. * @throws {MongoError} If operation cannot be added to bulk write
  662. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  663. */
  664. replaceOne(replacement) {
  665. // Perform upsert
  666. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  667. // Establish the update command
  668. const document = {
  669. q: this.s.currentOp.selector,
  670. u: replacement,
  671. multi: false,
  672. upsert: upsert
  673. };
  674. if (replacement.hint) {
  675. document.hint = replacement.hint;
  676. }
  677. if (hasAtomicOperators(replacement)) {
  678. throw new TypeError('Replacement document must not use atomic operators');
  679. }
  680. // Clear out current Op
  681. this.s.currentOp = null;
  682. return this.s.options.addToOperationsList(this, UPDATE, document);
  683. }
  684. /**
  685. * Upsert modifier for update bulk operation, noting that this operation is an upsert.
  686. *
  687. * @method
  688. * @throws {MongoError} If operation cannot be added to bulk write
  689. * @return {FindOperators} reference to self
  690. */
  691. upsert() {
  692. this.s.currentOp.upsert = true;
  693. return this;
  694. }
  695. /**
  696. * Add a delete one operation to the bulk operation
  697. *
  698. * @method
  699. * @throws {MongoError} If operation cannot be added to bulk write
  700. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  701. */
  702. deleteOne() {
  703. // Establish the update command
  704. const document = {
  705. q: this.s.currentOp.selector,
  706. limit: 1
  707. };
  708. // Clear out current Op
  709. this.s.currentOp = null;
  710. return this.s.options.addToOperationsList(this, REMOVE, document);
  711. }
  712. /**
  713. * Add a delete many operation to the bulk operation
  714. *
  715. * @method
  716. * @throws {MongoError} If operation cannot be added to bulk write
  717. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  718. */
  719. delete() {
  720. // Establish the update command
  721. const document = {
  722. q: this.s.currentOp.selector,
  723. limit: 0
  724. };
  725. // Clear out current Op
  726. this.s.currentOp = null;
  727. return this.s.options.addToOperationsList(this, REMOVE, document);
  728. }
  729. /**
  730. * backwards compatability for deleteOne
  731. * @deprecated
  732. */
  733. removeOne() {
  734. emitWarningOnce('bulk operation `removeOne` has been deprecated, please use `deleteOne`');
  735. return this.deleteOne();
  736. }
  737. /**
  738. * backwards compatability for delete
  739. * @deprecated
  740. */
  741. remove() {
  742. emitWarningOnce('bulk operation `remove` has been deprecated, please use `delete`');
  743. return this.delete();
  744. }
  745. }
  746. /**
  747. * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation
  748. *
  749. * **NOTE:** Internal Type, do not instantiate directly
  750. */
  751. class BulkOperationBase {
  752. /**
  753. * Create a new OrderedBulkOperation or UnorderedBulkOperation instance
  754. * @property {number} length Get the number of operations in the bulk.
  755. */
  756. constructor(topology, collection, options, isOrdered) {
  757. // determine whether bulkOperation is ordered or unordered
  758. this.isOrdered = isOrdered;
  759. options = options == null ? {} : options;
  760. // TODO Bring from driver information in isMaster
  761. // Get the namespace for the write operations
  762. const namespace = collection.s.namespace;
  763. // Used to mark operation as executed
  764. const executed = false;
  765. // Current item
  766. const currentOp = null;
  767. // Handle to the bson serializer, used to calculate running sizes
  768. const bson = topology.bson;
  769. // Set max byte size
  770. const isMaster = topology.lastIsMaster();
  771. // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents
  772. // over 2mb are still allowed
  773. const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);
  774. const maxBsonObjectSize =
  775. isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16;
  776. const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;
  777. const maxWriteBatchSize =
  778. isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000;
  779. // Calculates the largest possible size of an Array key, represented as a BSON string
  780. // element. This calculation:
  781. // 1 byte for BSON type
  782. // # of bytes = length of (string representation of (maxWriteBatchSize - 1))
  783. // + 1 bytes for null terminator
  784. const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
  785. // Final options for retryable writes and write concern
  786. let finalOptions = Object.assign({}, options);
  787. finalOptions = applyRetryableWrites(finalOptions, collection.s.db);
  788. finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options);
  789. const writeConcern = finalOptions.writeConcern;
  790. // Get the promiseLibrary
  791. const promiseLibrary = options.promiseLibrary || Promise;
  792. // Final results
  793. const bulkResult = {
  794. ok: 1,
  795. writeErrors: [],
  796. writeConcernErrors: [],
  797. insertedIds: [],
  798. nInserted: 0,
  799. nUpserted: 0,
  800. nMatched: 0,
  801. nModified: 0,
  802. nRemoved: 0,
  803. upserted: []
  804. };
  805. // Internal state
  806. this.s = {
  807. // Final result
  808. bulkResult: bulkResult,
  809. // Current batch state
  810. currentBatch: null,
  811. currentIndex: 0,
  812. // ordered specific
  813. currentBatchSize: 0,
  814. currentBatchSizeBytes: 0,
  815. // unordered specific
  816. currentInsertBatch: null,
  817. currentUpdateBatch: null,
  818. currentRemoveBatch: null,
  819. batches: [],
  820. // Write concern
  821. writeConcern: writeConcern,
  822. // Max batch size options
  823. maxBsonObjectSize,
  824. maxBatchSizeBytes,
  825. maxWriteBatchSize,
  826. maxKeySize,
  827. // Namespace
  828. namespace: namespace,
  829. // BSON
  830. bson: bson,
  831. // Topology
  832. topology: topology,
  833. // Options
  834. options: finalOptions,
  835. // Current operation
  836. currentOp: currentOp,
  837. // Executed
  838. executed: executed,
  839. // Collection
  840. collection: collection,
  841. // Promise Library
  842. promiseLibrary: promiseLibrary,
  843. // Fundamental error
  844. err: null,
  845. // check keys
  846. checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true
  847. };
  848. // bypass Validation
  849. if (options.bypassDocumentValidation === true) {
  850. this.s.bypassDocumentValidation = true;
  851. }
  852. }
  853. /**
  854. * Add a single insert document to the bulk operation
  855. *
  856. * @param {object} document the document to insert
  857. * @throws {MongoError}
  858. * @return {BulkOperationBase} A reference to self
  859. *
  860. * @example
  861. * const bulkOp = collection.initializeOrderedBulkOp();
  862. * // Adds three inserts to the bulkOp.
  863. * bulkOp
  864. * .insert({ a: 1 })
  865. * .insert({ b: 2 })
  866. * .insert({ c: 3 });
  867. * await bulkOp.execute();
  868. */
  869. insert(document) {
  870. if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null)
  871. document._id = new ObjectID();
  872. return this.s.options.addToOperationsList(this, INSERT, document);
  873. }
  874. /**
  875. * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
  876. * Returns a builder object used to complete the definition of the operation.
  877. *
  878. * @method
  879. * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation}
  880. * @throws {MongoError} if a selector is not specified
  881. * @return {FindOperators} A helper object with which the write operation can be defined.
  882. *
  883. * @example
  884. * const bulkOp = collection.initializeOrderedBulkOp();
  885. *
  886. * // Add an updateOne to the bulkOp
  887. * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
  888. *
  889. * // Add an updateMany to the bulkOp
  890. * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
  891. *
  892. * // Add an upsert
  893. * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
  894. *
  895. * // Add a deletion
  896. * bulkOp.find({ g: 7 }).deleteOne();
  897. *
  898. * // Add a multi deletion
  899. * bulkOp.find({ h: 8 }).delete();
  900. *
  901. * // Add a replaceOne
  902. * bulkOp.find({ i: 9 }).replaceOne({ j: 10 });
  903. *
  904. * // Update using a pipeline (requires Mongodb 4.2 or higher)
  905. * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
  906. * { $set: { total: { $sum: [ '$y', '$z' ] } } }
  907. * ]);
  908. *
  909. * // All of the ops will now be executed
  910. * await bulkOp.execute();
  911. */
  912. find(selector) {
  913. if (!selector) {
  914. throw toError('Bulk find operation must specify a selector');
  915. }
  916. // Save a current selector
  917. this.s.currentOp = {
  918. selector: selector
  919. };
  920. return new FindOperators(this);
  921. }
  922. /**
  923. * Specifies a raw operation to perform in the bulk write.
  924. *
  925. * @method
  926. * @param {object} op The raw operation to perform.
  927. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  928. * @return {BulkOperationBase} A reference to self
  929. */
  930. raw(op) {
  931. const key = Object.keys(op)[0];
  932. // Set up the force server object id
  933. const forceServerObjectId =
  934. typeof this.s.options.forceServerObjectId === 'boolean'
  935. ? this.s.options.forceServerObjectId
  936. : this.s.collection.s.db.options.forceServerObjectId;
  937. // Update operations
  938. if (
  939. (op.updateOne && op.updateOne.q) ||
  940. (op.updateMany && op.updateMany.q) ||
  941. (op.replaceOne && op.replaceOne.q)
  942. ) {
  943. op[key].multi = op.updateOne || op.replaceOne ? false : true;
  944. return this.s.options.addToOperationsList(this, UPDATE, op[key]);
  945. }
  946. // Crud spec update format
  947. if (op.updateOne || op.updateMany || op.replaceOne) {
  948. if (op.replaceOne && hasAtomicOperators(op[key].replacement)) {
  949. throw new TypeError('Replacement document must not use atomic operators');
  950. } else if ((op.updateOne || op.updateMany) && !hasAtomicOperators(op[key].update)) {
  951. throw new TypeError('Update document requires atomic operators');
  952. }
  953. const multi = op.updateOne || op.replaceOne ? false : true;
  954. const operation = {
  955. q: op[key].filter,
  956. u: op[key].update || op[key].replacement,
  957. multi: multi
  958. };
  959. if (op[key].hint) {
  960. operation.hint = op[key].hint;
  961. }
  962. if (this.isOrdered) {
  963. operation.upsert = op[key].upsert ? true : false;
  964. if (op.collation) operation.collation = op.collation;
  965. } else {
  966. if (op[key].upsert) operation.upsert = true;
  967. }
  968. if (op[key].arrayFilters) {
  969. // TODO: this check should be done at command construction against a connection, not a topology
  970. if (maxWireVersion(this.s.topology) < 6) {
  971. throw new TypeError('arrayFilters are only supported on MongoDB 3.6+');
  972. }
  973. operation.arrayFilters = op[key].arrayFilters;
  974. }
  975. return this.s.options.addToOperationsList(this, UPDATE, operation);
  976. }
  977. // Remove operations
  978. if (
  979. op.removeOne ||
  980. op.removeMany ||
  981. (op.deleteOne && op.deleteOne.q) ||
  982. (op.deleteMany && op.deleteMany.q)
  983. ) {
  984. op[key].limit = op.removeOne ? 1 : 0;
  985. return this.s.options.addToOperationsList(this, REMOVE, op[key]);
  986. }
  987. // Crud spec delete operations, less efficient
  988. if (op.deleteOne || op.deleteMany) {
  989. const limit = op.deleteOne ? 1 : 0;
  990. const operation = { q: op[key].filter, limit: limit };
  991. if (op[key].hint) {
  992. operation.hint = op[key].hint;
  993. }
  994. if (this.isOrdered) {
  995. if (op.collation) operation.collation = op.collation;
  996. }
  997. return this.s.options.addToOperationsList(this, REMOVE, operation);
  998. }
  999. // Insert operations
  1000. if (op.insertOne && op.insertOne.document == null) {
  1001. if (forceServerObjectId !== true && op.insertOne._id == null)
  1002. op.insertOne._id = new ObjectID();
  1003. return this.s.options.addToOperationsList(this, INSERT, op.insertOne);
  1004. } else if (op.insertOne && op.insertOne.document) {
  1005. if (forceServerObjectId !== true && op.insertOne.document._id == null)
  1006. op.insertOne.document._id = new ObjectID();
  1007. return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document);
  1008. }
  1009. if (op.insertMany) {
  1010. emitWarningOnce(
  1011. 'bulk operation `insertMany` has been deprecated; use multiple `insertOne` ops instead'
  1012. );
  1013. for (let i = 0; i < op.insertMany.length; i++) {
  1014. if (forceServerObjectId !== true && op.insertMany[i]._id == null)
  1015. op.insertMany[i]._id = new ObjectID();
  1016. this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]);
  1017. }
  1018. return;
  1019. }
  1020. // No valid type of operation
  1021. throw toError(
  1022. 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'
  1023. );
  1024. }
  1025. /**
  1026. * helper function to assist with promiseOrCallback behavior
  1027. * @ignore
  1028. * @param {*} err
  1029. * @param {*} callback
  1030. */
  1031. _handleEarlyError(err, callback) {
  1032. if (typeof callback === 'function') {
  1033. callback(err, null);
  1034. return;
  1035. }
  1036. return this.s.promiseLibrary.reject(err);
  1037. }
  1038. /**
  1039. * An internal helper method. Do not invoke directly. Will be going away in the future
  1040. *
  1041. * @ignore
  1042. * @method
  1043. * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation
  1044. * @param {object} writeConcern
  1045. * @param {object} options
  1046. * @param {function} callback
  1047. */
  1048. bulkExecute(_writeConcern, options, callback) {
  1049. if (typeof options === 'function') {
  1050. callback = options;
  1051. }
  1052. const finalOptions = Object.assign({}, this.s.options, options);
  1053. if (typeof _writeConcern === 'function') {
  1054. callback = _writeConcern;
  1055. } else if (_writeConcern && typeof _writeConcern === 'object') {
  1056. this.s.writeConcern = _writeConcern;
  1057. }
  1058. if (this.s.executed) {
  1059. const executedError = toError('batch cannot be re-executed');
  1060. return this._handleEarlyError(executedError, callback);
  1061. }
  1062. // If we have current batch
  1063. if (this.isOrdered) {
  1064. if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
  1065. } else {
  1066. if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
  1067. if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
  1068. if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
  1069. }
  1070. // If we have no operations in the bulk raise an error
  1071. if (this.s.batches.length === 0) {
  1072. const emptyBatchError = toError('Invalid Operation, no operations specified');
  1073. return this._handleEarlyError(emptyBatchError, callback);
  1074. }
  1075. return { options: finalOptions, callback };
  1076. }
  1077. /**
  1078. * The callback format for results
  1079. * @callback BulkOperationBase~resultCallback
  1080. * @param {MongoError} error An error instance representing the error during the execution.
  1081. * @param {BulkWriteResult} result The bulk write result.
  1082. */
  1083. /**
  1084. * Execute the bulk operation
  1085. *
  1086. * @method
  1087. * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options.
  1088. * @param {object} [options] Optional settings.
  1089. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1090. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1091. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1092. * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead.
  1093. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1094. * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors
  1095. * @throws {MongoError} Throws error if the bulk object has already been executed
  1096. * @throws {MongoError} Throws error if the bulk object does not have any operations
  1097. * @return {Promise|void} returns Promise if no callback passed
  1098. */
  1099. execute(_writeConcern, options, callback) {
  1100. const ret = this.bulkExecute(_writeConcern, options, callback);
  1101. if (!ret || isPromiseLike(ret)) {
  1102. return ret;
  1103. }
  1104. options = ret.options;
  1105. callback = ret.callback;
  1106. return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);
  1107. }
  1108. /**
  1109. * Handles final options before executing command
  1110. *
  1111. * An internal method. Do not invoke. Will not be accessible in the future
  1112. *
  1113. * @ignore
  1114. * @param {object} config
  1115. * @param {object} config.options
  1116. * @param {number} config.batch
  1117. * @param {function} config.resultHandler
  1118. * @param {function} callback
  1119. */
  1120. finalOptionsHandler(config, callback) {
  1121. const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options);
  1122. if (this.s.writeConcern != null) {
  1123. finalOptions.writeConcern = this.s.writeConcern;
  1124. }
  1125. if (finalOptions.bypassDocumentValidation !== true) {
  1126. delete finalOptions.bypassDocumentValidation;
  1127. }
  1128. // Set an operationIf if provided
  1129. if (this.operationId) {
  1130. config.resultHandler.operationId = this.operationId;
  1131. }
  1132. // Serialize functions
  1133. if (this.s.options.serializeFunctions) {
  1134. finalOptions.serializeFunctions = true;
  1135. }
  1136. // Ignore undefined
  1137. if (this.s.options.ignoreUndefined) {
  1138. finalOptions.ignoreUndefined = true;
  1139. }
  1140. // Is the bypassDocumentValidation options specific
  1141. if (this.s.bypassDocumentValidation === true) {
  1142. finalOptions.bypassDocumentValidation = true;
  1143. }
  1144. // Is the checkKeys option disabled
  1145. if (this.s.checkKeys === false) {
  1146. finalOptions.checkKeys = false;
  1147. }
  1148. if (finalOptions.retryWrites) {
  1149. if (config.batch.batchType === UPDATE) {
  1150. finalOptions.retryWrites =
  1151. finalOptions.retryWrites && !config.batch.operations.some(op => op.multi);
  1152. }
  1153. if (config.batch.batchType === REMOVE) {
  1154. finalOptions.retryWrites =
  1155. finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0);
  1156. }
  1157. }
  1158. try {
  1159. if (config.batch.batchType === INSERT) {
  1160. this.s.topology.insert(
  1161. this.s.namespace,
  1162. config.batch.operations,
  1163. finalOptions,
  1164. config.resultHandler
  1165. );
  1166. } else if (config.batch.batchType === UPDATE) {
  1167. this.s.topology.update(
  1168. this.s.namespace,
  1169. config.batch.operations,
  1170. finalOptions,
  1171. config.resultHandler
  1172. );
  1173. } else if (config.batch.batchType === REMOVE) {
  1174. this.s.topology.remove(
  1175. this.s.namespace,
  1176. config.batch.operations,
  1177. finalOptions,
  1178. config.resultHandler
  1179. );
  1180. }
  1181. } catch (err) {
  1182. // Force top level error
  1183. err.ok = 0;
  1184. // Merge top level error and return
  1185. handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null));
  1186. }
  1187. }
  1188. /**
  1189. * Handles the write error before executing commands
  1190. *
  1191. * An internal helper method. Do not invoke directly. Will be going away in the future
  1192. *
  1193. * @ignore
  1194. * @param {function} callback
  1195. * @param {BulkWriteResult} writeResult
  1196. * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation
  1197. */
  1198. handleWriteError(callback, writeResult) {
  1199. if (this.s.bulkResult.writeErrors.length > 0) {
  1200. const msg = this.s.bulkResult.writeErrors[0].errmsg
  1201. ? this.s.bulkResult.writeErrors[0].errmsg
  1202. : 'write operation failed';
  1203. handleCallback(
  1204. callback,
  1205. new BulkWriteError(
  1206. toError({
  1207. message: msg,
  1208. code: this.s.bulkResult.writeErrors[0].code,
  1209. writeErrors: this.s.bulkResult.writeErrors
  1210. }),
  1211. writeResult
  1212. ),
  1213. null
  1214. );
  1215. return true;
  1216. }
  1217. if (writeResult.getWriteConcernError()) {
  1218. handleCallback(
  1219. callback,
  1220. new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult),
  1221. null
  1222. );
  1223. return true;
  1224. }
  1225. }
  1226. }
  1227. Object.defineProperty(BulkOperationBase.prototype, 'length', {
  1228. enumerable: true,
  1229. get: function() {
  1230. return this.s.currentIndex;
  1231. }
  1232. });
  1233. // Exports symbols
  1234. module.exports = {
  1235. Batch,
  1236. BulkOperationBase,
  1237. mergeBatchResults,
  1238. bson,
  1239. INSERT: INSERT,
  1240. UPDATE: UPDATE,
  1241. REMOVE: REMOVE,
  1242. BulkWriteError,
  1243. BulkWriteResult
  1244. };