Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.js 28KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. 'use strict';
  2. const Long = require('mongodb-core').BSON.Long;
  3. const MongoError = require('mongodb-core').MongoError;
  4. const toError = require('../utils').toError;
  5. const handleCallback = require('../utils').handleCallback;
  6. const applyRetryableWrites = require('../utils').applyRetryableWrites;
  7. const applyWriteConcern = require('../utils').applyWriteConcern;
  8. const ObjectID = require('mongodb-core').BSON.ObjectID;
  9. const BSON = require('mongodb-core').BSON;
  10. // Error codes
  11. const UNKNOWN_ERROR = 8;
  12. const INVALID_BSON_ERROR = 22;
  13. const WRITE_CONCERN_ERROR = 64;
  14. const MULTIPLE_ERROR = 65;
  15. // Insert types
  16. const INSERT = 1;
  17. const UPDATE = 2;
  18. const REMOVE = 3;
  19. const bson = new BSON([
  20. BSON.Binary,
  21. BSON.Code,
  22. BSON.DBRef,
  23. BSON.Decimal128,
  24. BSON.Double,
  25. BSON.Int32,
  26. BSON.Long,
  27. BSON.Map,
  28. BSON.MaxKey,
  29. BSON.MinKey,
  30. BSON.ObjectId,
  31. BSON.BSONRegExp,
  32. BSON.Symbol,
  33. BSON.Timestamp
  34. ]);
  35. /**
  36. * Keeps the state of a unordered batch so we can rewrite the results
  37. * correctly after command execution
  38. * @ignore
  39. */
  40. class Batch {
  41. constructor(batchType, originalZeroIndex) {
  42. this.originalZeroIndex = originalZeroIndex;
  43. this.currentIndex = 0;
  44. this.originalIndexes = [];
  45. this.batchType = batchType;
  46. this.operations = [];
  47. this.size = 0;
  48. this.sizeBytes = 0;
  49. }
  50. }
  51. /**
  52. * Wraps a legacy operation so we can correctly rewrite it's error
  53. * @ignore
  54. */
  55. class LegacyOp {
  56. constructor(batchType, operation, index) {
  57. this.batchType = batchType;
  58. this.index = index;
  59. this.operation = operation;
  60. }
  61. }
  62. /**
  63. * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly)
  64. *
  65. * @class
  66. * @return {BulkWriteResult} a BulkWriteResult instance
  67. */
  68. class BulkWriteResult {
  69. constructor(bulkResult) {
  70. this.result = bulkResult;
  71. }
  72. /**
  73. * @return {boolean} ok Did bulk operation correctly execute
  74. */
  75. get ok() {
  76. return this.result.ok;
  77. }
  78. /**
  79. * @return {number} nInserted number of inserted documents
  80. */
  81. get nInserted() {
  82. return this.result.nInserted;
  83. }
  84. /**
  85. * @return {number} nUpserted Number of upserted documents
  86. */
  87. get nUpserted() {
  88. return this.result.nUpserted;
  89. }
  90. /**
  91. * @return {number} nMatched Number of matched documents
  92. */
  93. get nMatched() {
  94. return this.result.nMatched;
  95. }
  96. /**
  97. * @return {number} nModified Number of documents updated physically on disk
  98. */
  99. get nModified() {
  100. return this.result.nModified;
  101. }
  102. /**
  103. * @return {number} nRemoved Number of removed documents
  104. */
  105. get nRemoved() {
  106. return this.result.nRemoved;
  107. }
  108. /**
  109. * Return an array of inserted ids
  110. *
  111. * @return {object[]}
  112. */
  113. getInsertedIds() {
  114. return this.result.insertedIds;
  115. }
  116. /**
  117. * Return an array of upserted ids
  118. *
  119. * @return {object[]}
  120. */
  121. getUpsertedIds() {
  122. return this.result.upserted;
  123. }
  124. /**
  125. * Return the upserted id at position x
  126. *
  127. * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index
  128. * @return {object}
  129. */
  130. getUpsertedIdAt(index) {
  131. return this.result.upserted[index];
  132. }
  133. /**
  134. * Return raw internal result
  135. *
  136. * @return {object}
  137. */
  138. getRawResponse() {
  139. return this.result;
  140. }
  141. /**
  142. * Returns true if the bulk operation contains a write error
  143. *
  144. * @return {boolean}
  145. */
  146. hasWriteErrors() {
  147. return this.result.writeErrors.length > 0;
  148. }
  149. /**
  150. * Returns the number of write errors off the bulk operation
  151. *
  152. * @return {number}
  153. */
  154. getWriteErrorCount() {
  155. return this.result.writeErrors.length;
  156. }
  157. /**
  158. * Returns a specific write error object
  159. *
  160. * @param {number} index of the write error to return, returns null if there is no result for passed in index
  161. * @return {WriteError}
  162. */
  163. getWriteErrorAt(index) {
  164. if (index < this.result.writeErrors.length) {
  165. return this.result.writeErrors[index];
  166. }
  167. return null;
  168. }
  169. /**
  170. * Retrieve all write errors
  171. *
  172. * @return {object[]}
  173. */
  174. getWriteErrors() {
  175. return this.result.writeErrors;
  176. }
  177. /**
  178. * Retrieve lastOp if available
  179. *
  180. * @return {object}
  181. */
  182. getLastOp() {
  183. return this.result.lastOp;
  184. }
  185. /**
  186. * Retrieve the write concern error if any
  187. *
  188. * @return {WriteConcernError}
  189. */
  190. getWriteConcernError() {
  191. if (this.result.writeConcernErrors.length === 0) {
  192. return null;
  193. } else if (this.result.writeConcernErrors.length === 1) {
  194. // Return the error
  195. return this.result.writeConcernErrors[0];
  196. } else {
  197. // Combine the errors
  198. let errmsg = '';
  199. for (let i = 0; i < this.result.writeConcernErrors.length; i++) {
  200. const err = this.result.writeConcernErrors[i];
  201. errmsg = errmsg + err.errmsg;
  202. // TODO: Something better
  203. if (i === 0) errmsg = errmsg + ' and ';
  204. }
  205. return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR });
  206. }
  207. }
  208. /**
  209. * @return {BulkWriteResult} a BulkWriteResult instance
  210. */
  211. toJSON() {
  212. return this.result;
  213. }
  214. /**
  215. * @return {string}
  216. */
  217. toString() {
  218. return `BulkWriteResult(${this.toJSON(this.result)})`;
  219. }
  220. /**
  221. * @return {boolean}
  222. */
  223. isOk() {
  224. return this.result.ok === 1;
  225. }
  226. }
  227. /**
  228. * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly)
  229. *
  230. * @class
  231. * @return {WriteConcernError} a WriteConcernError instance
  232. */
  233. class WriteConcernError {
  234. constructor(err) {
  235. this.err = err;
  236. }
  237. /**
  238. * @return {number} code Write concern error code.
  239. */
  240. get code() {
  241. return this.err.code;
  242. }
  243. /**
  244. * @return {string} errmsg Write concern error message.
  245. */
  246. get errmsg() {
  247. return this.err.errmsg;
  248. }
  249. /**
  250. * @return {object}
  251. */
  252. toJSON() {
  253. return { code: this.err.code, errmsg: this.err.errmsg };
  254. }
  255. /**
  256. * @return {string}
  257. */
  258. toString() {
  259. return `WriteConcernError(${this.err.errmsg})`;
  260. }
  261. }
  262. /**
  263. * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly)
  264. *
  265. * @class
  266. * @return {WriteConcernError} a WriteConcernError instance
  267. */
  268. class WriteError {
  269. constructor(err) {
  270. this.err = err;
  271. }
  272. /**
  273. * @return {number} code Write concern error code.
  274. */
  275. get code() {
  276. return this.err.code;
  277. }
  278. /**
  279. * @return {number} index Write concern error original bulk operation index.
  280. */
  281. get index() {
  282. return this.err.index;
  283. }
  284. /**
  285. * @return {string} errmsg Write concern error message.
  286. */
  287. get errmsg() {
  288. return this.err.errmsg;
  289. }
  290. /**
  291. * Define access methods
  292. * @return {object}
  293. */
  294. getOperation() {
  295. return this.err.op;
  296. }
  297. /**
  298. * @return {object}
  299. */
  300. toJSON() {
  301. return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
  302. }
  303. /**
  304. * @return {string}
  305. */
  306. toString() {
  307. return `WriteError(${JSON.stringify(this.toJSON())})`;
  308. }
  309. }
  310. /**
  311. * Merges results into shared data structure
  312. * @ignore
  313. */
  314. function mergeBatchResults(ordered, batch, bulkResult, err, result) {
  315. // If we have an error set the result to be the err object
  316. if (err) {
  317. result = err;
  318. } else if (result && result.result) {
  319. result = result.result;
  320. } else if (result == null) {
  321. return;
  322. }
  323. // Do we have a top level error stop processing and return
  324. if (result.ok === 0 && bulkResult.ok === 1) {
  325. bulkResult.ok = 0;
  326. const writeError = {
  327. index: 0,
  328. code: result.code || 0,
  329. errmsg: result.message,
  330. op: batch.operations[0]
  331. };
  332. bulkResult.writeErrors.push(new WriteError(writeError));
  333. return;
  334. } else if (result.ok === 0 && bulkResult.ok === 0) {
  335. return;
  336. }
  337. // Deal with opTime if available
  338. if (result.opTime || result.lastOp) {
  339. const opTime = result.lastOp || result.opTime;
  340. let lastOpTS = null;
  341. let lastOpT = null;
  342. // We have a time stamp
  343. if (opTime && opTime._bsontype === 'Timestamp') {
  344. if (bulkResult.lastOp == null) {
  345. bulkResult.lastOp = opTime;
  346. } else if (opTime.greaterThan(bulkResult.lastOp)) {
  347. bulkResult.lastOp = opTime;
  348. }
  349. } else {
  350. // Existing TS
  351. if (bulkResult.lastOp) {
  352. lastOpTS =
  353. typeof bulkResult.lastOp.ts === 'number'
  354. ? Long.fromNumber(bulkResult.lastOp.ts)
  355. : bulkResult.lastOp.ts;
  356. lastOpT =
  357. typeof bulkResult.lastOp.t === 'number'
  358. ? Long.fromNumber(bulkResult.lastOp.t)
  359. : bulkResult.lastOp.t;
  360. }
  361. // Current OpTime TS
  362. const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts;
  363. const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t;
  364. // Compare the opTime's
  365. if (bulkResult.lastOp == null) {
  366. bulkResult.lastOp = opTime;
  367. } else if (opTimeTS.greaterThan(lastOpTS)) {
  368. bulkResult.lastOp = opTime;
  369. } else if (opTimeTS.equals(lastOpTS)) {
  370. if (opTimeT.greaterThan(lastOpT)) {
  371. bulkResult.lastOp = opTime;
  372. }
  373. }
  374. }
  375. }
  376. // If we have an insert Batch type
  377. if (batch.batchType === INSERT && result.n) {
  378. bulkResult.nInserted = bulkResult.nInserted + result.n;
  379. }
  380. // If we have an insert Batch type
  381. if (batch.batchType === REMOVE && result.n) {
  382. bulkResult.nRemoved = bulkResult.nRemoved + result.n;
  383. }
  384. let nUpserted = 0;
  385. // We have an array of upserted values, we need to rewrite the indexes
  386. if (Array.isArray(result.upserted)) {
  387. nUpserted = result.upserted.length;
  388. for (let i = 0; i < result.upserted.length; i++) {
  389. bulkResult.upserted.push({
  390. index: result.upserted[i].index + batch.originalZeroIndex,
  391. _id: result.upserted[i]._id
  392. });
  393. }
  394. } else if (result.upserted) {
  395. nUpserted = 1;
  396. bulkResult.upserted.push({
  397. index: batch.originalZeroIndex,
  398. _id: result.upserted
  399. });
  400. }
  401. // If we have an update Batch type
  402. if (batch.batchType === UPDATE && result.n) {
  403. const nModified = result.nModified;
  404. bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
  405. bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
  406. if (typeof nModified === 'number') {
  407. bulkResult.nModified = bulkResult.nModified + nModified;
  408. } else {
  409. bulkResult.nModified = null;
  410. }
  411. }
  412. if (Array.isArray(result.writeErrors)) {
  413. for (let i = 0; i < result.writeErrors.length; i++) {
  414. const writeError = {
  415. index: batch.originalZeroIndex + result.writeErrors[i].index,
  416. code: result.writeErrors[i].code,
  417. errmsg: result.writeErrors[i].errmsg,
  418. op: batch.operations[result.writeErrors[i].index]
  419. };
  420. bulkResult.writeErrors.push(new WriteError(writeError));
  421. }
  422. }
  423. if (result.writeConcernError) {
  424. bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
  425. }
  426. }
  427. /**
  428. * handles write concern error
  429. *
  430. * @param {object} batch
  431. * @param {object} bulkResult
  432. * @param {boolean} ordered
  433. * @param {WriteConcernError} err
  434. * @param {function} callback
  435. */
  436. function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) {
  437. mergeBatchResults(ordered, batch, bulkResult, null, err.result);
  438. const wrappedWriteConcernError = new WriteConcernError({
  439. errmsg: err.result.writeConcernError.errmsg,
  440. code: err.result.writeConcernError.result
  441. });
  442. return handleCallback(
  443. callback,
  444. new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
  445. null
  446. );
  447. }
  448. /**
  449. * Creates a new BulkWriteError
  450. *
  451. * @class
  452. * @param {Error|string|object} message The error message
  453. * @param {BulkWriteResult} result The result of the bulk write operation
  454. * @return {BulkWriteError} A BulkWriteError instance
  455. * @extends {MongoError}
  456. */
  457. class BulkWriteError extends MongoError {
  458. constructor(error, result) {
  459. const message = error.err || error.errmsg || error.errMessage || error;
  460. super(message);
  461. Object.assign(this, error);
  462. this.name = 'BulkWriteError';
  463. this.result = result;
  464. }
  465. }
  466. /**
  467. * Handles the find operators for the bulk operations
  468. * @class
  469. */
  470. class FindOperators {
  471. /**
  472. * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation
  473. */
  474. constructor(bulkOperation) {
  475. this.s = bulkOperation.s;
  476. }
  477. /**
  478. * Add a single update document to the bulk operation
  479. *
  480. * @method
  481. * @param {object} updateDocument update operations
  482. * @throws {MongoError}
  483. * @return {OrderedBulkOperation|UnordedBulkOperation}
  484. */
  485. update(updateDocument) {
  486. // Perform upsert
  487. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  488. // Establish the update command
  489. const document = {
  490. q: this.s.currentOp.selector,
  491. u: updateDocument,
  492. multi: true,
  493. upsert: upsert
  494. };
  495. // Clear out current Op
  496. this.s.currentOp = null;
  497. return this.s.options.addToOperationsList(this, UPDATE, document);
  498. }
  499. /**
  500. * Add a single update one document to the bulk operation
  501. *
  502. * @method
  503. * @param {object} updateDocument update operations
  504. * @throws {MongoError}
  505. * @return {OrderedBulkOperation|UnordedBulkOperation}
  506. */
  507. updateOne(updateDocument) {
  508. // Perform upsert
  509. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  510. // Establish the update command
  511. const document = {
  512. q: this.s.currentOp.selector,
  513. u: updateDocument,
  514. multi: false,
  515. upsert: upsert
  516. };
  517. // Clear out current Op
  518. this.s.currentOp = null;
  519. return this.s.options.addToOperationsList(this, UPDATE, document);
  520. }
  521. /**
  522. * Add a replace one operation to the bulk operation
  523. *
  524. * @method
  525. * @param {object} updateDocument the new document to replace the existing one with
  526. * @throws {MongoError}
  527. * @return {OrderedBulkOperation|UnorderedBulkOperation}
  528. */
  529. replaceOne(updateDocument) {
  530. this.updateOne(updateDocument);
  531. }
  532. /**
  533. * Upsert modifier for update bulk operation
  534. *
  535. * @method
  536. * @throws {MongoError}
  537. * @return {FindOperators}
  538. */
  539. upsert() {
  540. this.s.currentOp.upsert = true;
  541. return this;
  542. }
  543. /**
  544. * Add a delete one operation to the bulk operation
  545. *
  546. * @method
  547. * @throws {MongoError}
  548. * @return {OrderedBulkOperation|UnordedBulkOperation}
  549. */
  550. deleteOne() {
  551. // Establish the update command
  552. const document = {
  553. q: this.s.currentOp.selector,
  554. limit: 1
  555. };
  556. // Clear out current Op
  557. this.s.currentOp = null;
  558. return this.s.options.addToOperationsList(this, REMOVE, document);
  559. }
  560. /**
  561. * Add a delete operation to the bulk operation
  562. *
  563. * @method
  564. * @throws {MongoError}
  565. * @return {OrderedBulkOperation|UnordedBulkOperation}
  566. */
  567. delete() {
  568. // Establish the update command
  569. const document = {
  570. q: this.s.currentOp.selector,
  571. limit: 0
  572. };
  573. // Clear out current Op
  574. this.s.currentOp = null;
  575. return this.s.options.addToOperationsList(this, REMOVE, document);
  576. }
  577. /**
  578. * backwards compatability for deleteOne
  579. */
  580. removeOne() {
  581. return this.deleteOne();
  582. }
  583. /**
  584. * backwards compatability for delete
  585. */
  586. remove() {
  587. return this.delete();
  588. }
  589. }
  590. /**
  591. * Parent class to OrderedBulkOperation and UnorderedBulkOperation
  592. * @class
  593. */
  594. class BulkOperationBase {
  595. /**
  596. * Create a new OrderedBulkOperation or UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
  597. * @class
  598. * @property {number} length Get the number of operations in the bulk.
  599. * @return {OrderedBulkOperation|UnordedBulkOperation}
  600. */
  601. constructor(topology, collection, options, isOrdered) {
  602. // determine whether bulkOperation is ordered or unordered
  603. this.isOrdered = isOrdered;
  604. options = options == null ? {} : options;
  605. // TODO Bring from driver information in isMaster
  606. // Get the namespace for the write operations
  607. const namespace = collection.collectionName;
  608. // Used to mark operation as executed
  609. const executed = false;
  610. // Current item
  611. const currentOp = null;
  612. // Handle to the bson serializer, used to calculate running sizes
  613. const bson = topology.bson;
  614. // Set max byte size
  615. const isMaster = topology.lastIsMaster();
  616. const maxBatchSizeBytes =
  617. isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16;
  618. const maxWriteBatchSize =
  619. isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000;
  620. // Final options for retryable writes and write concern
  621. let finalOptions = Object.assign({}, options);
  622. finalOptions = applyRetryableWrites(finalOptions, collection.s.db);
  623. finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options);
  624. const writeConcern = finalOptions.writeConcern;
  625. // Get the promiseLibrary
  626. const promiseLibrary = options.promiseLibrary || Promise;
  627. // Final results
  628. const bulkResult = {
  629. ok: 1,
  630. writeErrors: [],
  631. writeConcernErrors: [],
  632. insertedIds: [],
  633. nInserted: 0,
  634. nUpserted: 0,
  635. nMatched: 0,
  636. nModified: 0,
  637. nRemoved: 0,
  638. upserted: []
  639. };
  640. // Internal state
  641. this.s = {
  642. // Final result
  643. bulkResult: bulkResult,
  644. // Current batch state
  645. currentBatch: null,
  646. currentIndex: 0,
  647. // ordered specific
  648. currentBatchSize: 0,
  649. currentBatchSizeBytes: 0,
  650. // unordered specific
  651. currentInsertBatch: null,
  652. currentUpdateBatch: null,
  653. currentRemoveBatch: null,
  654. batches: [],
  655. // Write concern
  656. writeConcern: writeConcern,
  657. // Max batch size options
  658. maxBatchSizeBytes: maxBatchSizeBytes,
  659. maxWriteBatchSize: maxWriteBatchSize,
  660. // Namespace
  661. namespace: namespace,
  662. // BSON
  663. bson: bson,
  664. // Topology
  665. topology: topology,
  666. // Options
  667. options: finalOptions,
  668. // Current operation
  669. currentOp: currentOp,
  670. // Executed
  671. executed: executed,
  672. // Collection
  673. collection: collection,
  674. // Promise Library
  675. promiseLibrary: promiseLibrary,
  676. // Fundamental error
  677. err: null,
  678. // check keys
  679. checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true
  680. };
  681. // bypass Validation
  682. if (options.bypassDocumentValidation === true) {
  683. this.s.bypassDocumentValidation = true;
  684. }
  685. }
  686. /**
  687. * Add a single insert document to the bulk operation
  688. *
  689. * @param {object} document the document to insert
  690. * @throws {MongoError}
  691. * @return {OrderedBulkOperation|UnorderedBulkOperation}
  692. */
  693. insert(document) {
  694. if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null)
  695. document._id = new ObjectID();
  696. return this.s.options.addToOperationsList(this, INSERT, document);
  697. }
  698. /**
  699. * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
  700. *
  701. * @method
  702. * @param {object} selector The selector for the bulk operation.
  703. * @throws {MongoError}
  704. */
  705. find(selector) {
  706. if (!selector) {
  707. throw toError('Bulk find operation must specify a selector');
  708. }
  709. // Save a current selector
  710. this.s.currentOp = {
  711. selector: selector
  712. };
  713. return new FindOperators(this);
  714. }
  715. /**
  716. * Raw performs the bulk operation
  717. *
  718. * @method
  719. * @param {object} op operation
  720. * @return {OrderedBulkOperation|UnorderedBulkOperation}
  721. */
  722. raw(op) {
  723. const key = Object.keys(op)[0];
  724. // Set up the force server object id
  725. const forceServerObjectId =
  726. typeof this.s.options.forceServerObjectId === 'boolean'
  727. ? this.s.options.forceServerObjectId
  728. : this.s.collection.s.db.options.forceServerObjectId;
  729. // Update operations
  730. if (
  731. (op.updateOne && op.updateOne.q) ||
  732. (op.updateMany && op.updateMany.q) ||
  733. (op.replaceOne && op.replaceOne.q)
  734. ) {
  735. op[key].multi = op.updateOne || op.replaceOne ? false : true;
  736. return this.s.options.addToOperationsList(this, UPDATE, op[key]);
  737. }
  738. // Crud spec update format
  739. if (op.updateOne || op.updateMany || op.replaceOne) {
  740. const multi = op.updateOne || op.replaceOne ? false : true;
  741. const operation = {
  742. q: op[key].filter,
  743. u: op[key].update || op[key].replacement,
  744. multi: multi
  745. };
  746. if (this.isOrdered) {
  747. operation.upsert = op[key].upsert ? true : false;
  748. if (op.collation) operation.collation = op.collation;
  749. } else {
  750. if (op[key].upsert) operation.upsert = true;
  751. }
  752. if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters;
  753. return this.s.options.addToOperationsList(this, UPDATE, operation);
  754. }
  755. // Remove operations
  756. if (
  757. op.removeOne ||
  758. op.removeMany ||
  759. (op.deleteOne && op.deleteOne.q) ||
  760. (op.deleteMany && op.deleteMany.q)
  761. ) {
  762. op[key].limit = op.removeOne ? 1 : 0;
  763. return this.s.options.addToOperationsList(this, REMOVE, op[key]);
  764. }
  765. // Crud spec delete operations, less efficient
  766. if (op.deleteOne || op.deleteMany) {
  767. const limit = op.deleteOne ? 1 : 0;
  768. const operation = { q: op[key].filter, limit: limit };
  769. if (this.isOrdered) {
  770. if (op.collation) operation.collation = op.collation;
  771. }
  772. return this.s.options.addToOperationsList(this, REMOVE, operation);
  773. }
  774. // Insert operations
  775. if (op.insertOne && op.insertOne.document == null) {
  776. if (forceServerObjectId !== true && op.insertOne._id == null)
  777. op.insertOne._id = new ObjectID();
  778. return this.s.options.addToOperationsList(this, INSERT, op.insertOne);
  779. } else if (op.insertOne && op.insertOne.document) {
  780. if (forceServerObjectId !== true && op.insertOne.document._id == null)
  781. op.insertOne.document._id = new ObjectID();
  782. return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document);
  783. }
  784. if (op.insertMany) {
  785. for (let i = 0; i < op.insertMany.length; i++) {
  786. if (forceServerObjectId !== true && op.insertMany[i]._id == null)
  787. op.insertMany[i]._id = new ObjectID();
  788. this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]);
  789. }
  790. return;
  791. }
  792. // No valid type of operation
  793. throw toError(
  794. 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'
  795. );
  796. }
  797. /**
  798. * Execute next write command in a chain
  799. *
  800. * @method
  801. * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation
  802. * @param {object} writeConcern
  803. * @param {object} options
  804. * @param {function} callback
  805. */
  806. bulkExecute(_writeConcern, options, callback) {
  807. if (typeof options === 'function') (callback = options), (options = {});
  808. options = options || {};
  809. if (this.s.executed) {
  810. const executedError = toError('batch cannot be re-executed');
  811. return typeof callback === 'function'
  812. ? callback(executedError, null)
  813. : this.s.promiseLibrary.reject(executedError);
  814. }
  815. if (typeof _writeConcern === 'function') {
  816. callback = _writeConcern;
  817. } else if (_writeConcern && typeof _writeConcern === 'object') {
  818. this.s.writeConcern = _writeConcern;
  819. }
  820. // If we have current batch
  821. if (this.isOrdered) {
  822. if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
  823. } else {
  824. if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
  825. if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
  826. if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
  827. }
  828. // If we have no operations in the bulk raise an error
  829. if (this.s.batches.length === 0) {
  830. const emptyBatchError = toError('Invalid Operation, no operations specified');
  831. return typeof callback === 'function'
  832. ? callback(emptyBatchError, null)
  833. : this.s.promiseLibrary.reject(emptyBatchError);
  834. }
  835. return { options, callback };
  836. }
  837. /**
  838. * Handles final options before executing command
  839. *
  840. * @param {object} config
  841. * @param {object} config.options
  842. * @param {number} config.batch
  843. * @param {function} config.resultHandler
  844. * @param {function} callback
  845. */
  846. finalOptionsHandler(config, callback) {
  847. const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options);
  848. if (this.s.writeConcern != null) {
  849. finalOptions.writeConcern = this.s.writeConcern;
  850. }
  851. if (finalOptions.bypassDocumentValidation !== true) {
  852. delete finalOptions.bypassDocumentValidation;
  853. }
  854. // Set an operationIf if provided
  855. if (this.operationId) {
  856. config.resultHandler.operationId = this.operationId;
  857. }
  858. // Serialize functions
  859. if (this.s.options.serializeFunctions) {
  860. finalOptions.serializeFunctions = true;
  861. }
  862. // Ignore undefined
  863. if (this.s.options.ignoreUndefined) {
  864. finalOptions.ignoreUndefined = true;
  865. }
  866. // Is the bypassDocumentValidation options specific
  867. if (this.s.bypassDocumentValidation === true) {
  868. finalOptions.bypassDocumentValidation = true;
  869. }
  870. // Is the checkKeys option disabled
  871. if (this.s.checkKeys === false) {
  872. finalOptions.checkKeys = false;
  873. }
  874. if (finalOptions.retryWrites) {
  875. if (config.batch.batchType === UPDATE) {
  876. finalOptions.retryWrites =
  877. finalOptions.retryWrites && !config.batch.operations.some(op => op.multi);
  878. }
  879. if (config.batch.batchType === REMOVE) {
  880. finalOptions.retryWrites =
  881. finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0);
  882. }
  883. }
  884. try {
  885. if (config.batch.batchType === INSERT) {
  886. this.s.topology.insert(
  887. this.s.collection.namespace,
  888. config.batch.operations,
  889. finalOptions,
  890. config.resultHandler
  891. );
  892. } else if (config.batch.batchType === UPDATE) {
  893. this.s.topology.update(
  894. this.s.collection.namespace,
  895. config.batch.operations,
  896. finalOptions,
  897. config.resultHandler
  898. );
  899. } else if (config.batch.batchType === REMOVE) {
  900. this.s.topology.remove(
  901. this.s.collection.namespace,
  902. config.batch.operations,
  903. finalOptions,
  904. config.resultHandler
  905. );
  906. }
  907. } catch (err) {
  908. // Force top level error
  909. err.ok = 0;
  910. // Merge top level error and return
  911. handleCallback(
  912. callback,
  913. null,
  914. mergeBatchResults(false, config.batch, this.s.bulkResult, err, null)
  915. );
  916. }
  917. }
  918. /**
  919. * Handles the write error before executing commands
  920. *
  921. * @param {function} callback
  922. * @param {BulkWriteResult} writeResult
  923. * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation
  924. */
  925. handleWriteError(callback, writeResult) {
  926. if (this.s.bulkResult.writeErrors.length > 0) {
  927. if (this.s.bulkResult.writeErrors.length === 1) {
  928. handleCallback(
  929. callback,
  930. new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult),
  931. null
  932. );
  933. return true;
  934. }
  935. handleCallback(
  936. callback,
  937. new BulkWriteError(
  938. toError({
  939. message: 'write operation failed',
  940. code: this.s.bulkResult.writeErrors[0].code,
  941. writeErrors: this.s.bulkResult.writeErrors
  942. }),
  943. writeResult
  944. ),
  945. null
  946. );
  947. return true;
  948. } else if (writeResult.getWriteConcernError()) {
  949. handleCallback(
  950. callback,
  951. new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult),
  952. null
  953. );
  954. return true;
  955. }
  956. }
  957. }
  958. Object.defineProperty(BulkOperationBase.prototype, 'length', {
  959. enumerable: true,
  960. get: function() {
  961. return this.s.currentIndex;
  962. }
  963. });
  964. // Exports symbols
  965. module.exports = {
  966. Batch,
  967. BulkOperationBase,
  968. BulkWriteError,
  969. BulkWriteResult,
  970. bson,
  971. FindOperators,
  972. handleMongoWriteConcernError,
  973. LegacyOp,
  974. mergeBatchResults,
  975. INVALID_BSON_ERROR: INVALID_BSON_ERROR,
  976. MULTIPLE_ERROR: MULTIPLE_ERROR,
  977. UNKNOWN_ERROR: UNKNOWN_ERROR,
  978. WRITE_CONCERN_ERROR: WRITE_CONCERN_ERROR,
  979. INSERT: INSERT,
  980. UPDATE: UPDATE,
  981. REMOVE: REMOVE,
  982. WriteError,
  983. WriteConcernError
  984. };