Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

common.js 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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. * Merges results into shared data structure
  372. * @ignore
  373. */
  374. function mergeBatchResults(batch, bulkResult, err, result) {
  375. // If we have an error set the result to be the err object
  376. if (err) {
  377. result = err;
  378. } else if (result && result.result) {
  379. result = result.result;
  380. } else if (result == null) {
  381. return;
  382. }
  383. // Do we have a top level error stop processing and return
  384. if (result.ok === 0 && bulkResult.ok === 1) {
  385. bulkResult.ok = 0;
  386. const writeError = {
  387. index: 0,
  388. code: result.code || 0,
  389. errmsg: result.message,
  390. op: batch.operations[0]
  391. };
  392. bulkResult.writeErrors.push(new WriteError(writeError));
  393. return;
  394. } else if (result.ok === 0 && bulkResult.ok === 0) {
  395. return;
  396. }
  397. // Deal with opTime if available
  398. if (result.opTime || result.lastOp) {
  399. const opTime = result.lastOp || result.opTime;
  400. let lastOpTS = null;
  401. let lastOpT = null;
  402. // We have a time stamp
  403. if (opTime && opTime._bsontype === 'Timestamp') {
  404. if (bulkResult.lastOp == null) {
  405. bulkResult.lastOp = opTime;
  406. } else if (opTime.greaterThan(bulkResult.lastOp)) {
  407. bulkResult.lastOp = opTime;
  408. }
  409. } else {
  410. // Existing TS
  411. if (bulkResult.lastOp) {
  412. lastOpTS =
  413. typeof bulkResult.lastOp.ts === 'number'
  414. ? Long.fromNumber(bulkResult.lastOp.ts)
  415. : bulkResult.lastOp.ts;
  416. lastOpT =
  417. typeof bulkResult.lastOp.t === 'number'
  418. ? Long.fromNumber(bulkResult.lastOp.t)
  419. : bulkResult.lastOp.t;
  420. }
  421. // Current OpTime TS
  422. const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts;
  423. const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t;
  424. // Compare the opTime's
  425. if (bulkResult.lastOp == null) {
  426. bulkResult.lastOp = opTime;
  427. } else if (opTimeTS.greaterThan(lastOpTS)) {
  428. bulkResult.lastOp = opTime;
  429. } else if (opTimeTS.equals(lastOpTS)) {
  430. if (opTimeT.greaterThan(lastOpT)) {
  431. bulkResult.lastOp = opTime;
  432. }
  433. }
  434. }
  435. }
  436. // If we have an insert Batch type
  437. if (batch.batchType === INSERT && result.n) {
  438. bulkResult.nInserted = bulkResult.nInserted + result.n;
  439. }
  440. // If we have an insert Batch type
  441. if (batch.batchType === REMOVE && result.n) {
  442. bulkResult.nRemoved = bulkResult.nRemoved + result.n;
  443. }
  444. let nUpserted = 0;
  445. // We have an array of upserted values, we need to rewrite the indexes
  446. if (Array.isArray(result.upserted)) {
  447. nUpserted = result.upserted.length;
  448. for (let i = 0; i < result.upserted.length; i++) {
  449. bulkResult.upserted.push({
  450. index: result.upserted[i].index + batch.originalZeroIndex,
  451. _id: result.upserted[i]._id
  452. });
  453. }
  454. } else if (result.upserted) {
  455. nUpserted = 1;
  456. bulkResult.upserted.push({
  457. index: batch.originalZeroIndex,
  458. _id: result.upserted
  459. });
  460. }
  461. // If we have an update Batch type
  462. if (batch.batchType === UPDATE && result.n) {
  463. const nModified = result.nModified;
  464. bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
  465. bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
  466. if (typeof nModified === 'number') {
  467. bulkResult.nModified = bulkResult.nModified + nModified;
  468. } else {
  469. bulkResult.nModified = null;
  470. }
  471. }
  472. if (Array.isArray(result.writeErrors)) {
  473. for (let i = 0; i < result.writeErrors.length; i++) {
  474. const writeError = {
  475. index: batch.originalIndexes[result.writeErrors[i].index],
  476. code: result.writeErrors[i].code,
  477. errmsg: result.writeErrors[i].errmsg,
  478. op: batch.operations[result.writeErrors[i].index]
  479. };
  480. bulkResult.writeErrors.push(new WriteError(writeError));
  481. }
  482. }
  483. if (result.writeConcernError) {
  484. bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
  485. }
  486. }
  487. function executeCommands(bulkOperation, options, callback) {
  488. if (bulkOperation.s.batches.length === 0) {
  489. return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
  490. }
  491. const batch = bulkOperation.s.batches.shift();
  492. function resultHandler(err, result) {
  493. // Error is a driver related error not a bulk op error, terminate
  494. if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
  495. return handleCallback(callback, err);
  496. }
  497. // If we have and error
  498. if (err) err.ok = 0;
  499. if (err instanceof MongoWriteConcernError) {
  500. return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback);
  501. }
  502. // Merge the results together
  503. const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
  504. const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result);
  505. if (mergeResult != null) {
  506. return handleCallback(callback, null, writeResult);
  507. }
  508. if (bulkOperation.handleWriteError(callback, writeResult)) return;
  509. // Execute the next command in line
  510. executeCommands(bulkOperation, options, callback);
  511. }
  512. bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
  513. }
  514. /**
  515. * handles write concern error
  516. *
  517. * @ignore
  518. * @param {object} batch
  519. * @param {object} bulkResult
  520. * @param {boolean} ordered
  521. * @param {WriteConcernError} err
  522. * @param {function} callback
  523. */
  524. function handleMongoWriteConcernError(batch, bulkResult, err, callback) {
  525. mergeBatchResults(batch, bulkResult, null, err.result);
  526. const wrappedWriteConcernError = new WriteConcernError({
  527. errmsg: err.result.writeConcernError.errmsg,
  528. code: err.result.writeConcernError.result
  529. });
  530. return handleCallback(
  531. callback,
  532. new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
  533. null
  534. );
  535. }
  536. /**
  537. * @classdesc An error indicating an unsuccessful Bulk Write
  538. */
  539. class BulkWriteError extends MongoError {
  540. /**
  541. * Creates a new BulkWriteError
  542. *
  543. * @param {Error|string|object} message The error message
  544. * @param {BulkWriteResult} result The result of the bulk write operation
  545. * @extends {MongoError}
  546. */
  547. constructor(error, result) {
  548. const message = error.err || error.errmsg || error.errMessage || error;
  549. super(message);
  550. Object.assign(this, error);
  551. this.name = 'BulkWriteError';
  552. this.result = result;
  553. }
  554. /** Number of documents inserted. */
  555. get insertedCount() {
  556. return this.result.insertedCount;
  557. }
  558. /** Number of documents matched for update. */
  559. get matchedCount() {
  560. return this.result.matchedCount;
  561. }
  562. /** Number of documents modified. */
  563. get modifiedCount() {
  564. return this.result.modifiedCount;
  565. }
  566. /** Number of documents deleted. */
  567. get deletedCount() {
  568. return this.result.deletedCount;
  569. }
  570. /** Number of documents upserted. */
  571. get upsertedCount() {
  572. return this.result.upsertedCount;
  573. }
  574. /** Inserted document generated Id's, hash key is the index of the originating operation */
  575. get insertedIds() {
  576. return this.result.insertedIds;
  577. }
  578. /** Upserted document generated Id's, hash key is the index of the originating operation */
  579. get upsertedIds() {
  580. return this.result.upsertedIds;
  581. }
  582. }
  583. /**
  584. * @classdesc A builder object that is returned from {@link BulkOperationBase#find}.
  585. * Is used to build a write operation that involves a query filter.
  586. */
  587. class FindOperators {
  588. /**
  589. * Creates a new FindOperators object.
  590. *
  591. * **NOTE:** Internal Type, do not instantiate directly
  592. * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation
  593. */
  594. constructor(bulkOperation) {
  595. this.s = bulkOperation.s;
  596. }
  597. /**
  598. * Add a multiple update operation to the bulk operation
  599. *
  600. * @method
  601. * @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}
  602. * @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.
  603. * @throws {MongoError} If operation cannot be added to bulk write
  604. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  605. */
  606. update(updateDocument) {
  607. // Perform upsert
  608. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  609. // Establish the update command
  610. const document = {
  611. q: this.s.currentOp.selector,
  612. u: updateDocument,
  613. multi: true,
  614. upsert: upsert
  615. };
  616. if (updateDocument.hint) {
  617. document.hint = updateDocument.hint;
  618. }
  619. // Clear out current Op
  620. this.s.currentOp = null;
  621. return this.s.options.addToOperationsList(this, UPDATE, document);
  622. }
  623. /**
  624. * Add a single update operation to the bulk operation
  625. *
  626. * @method
  627. * @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}
  628. * @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.
  629. * @throws {MongoError} If operation cannot be added to bulk write
  630. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  631. */
  632. updateOne(updateDocument) {
  633. // Perform upsert
  634. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  635. // Establish the update command
  636. const document = {
  637. q: this.s.currentOp.selector,
  638. u: updateDocument,
  639. multi: false,
  640. upsert: upsert
  641. };
  642. if (updateDocument.hint) {
  643. document.hint = updateDocument.hint;
  644. }
  645. if (!hasAtomicOperators(updateDocument)) {
  646. throw new TypeError('Update document requires atomic operators');
  647. }
  648. // Clear out current Op
  649. this.s.currentOp = null;
  650. return this.s.options.addToOperationsList(this, UPDATE, document);
  651. }
  652. /**
  653. * Add a replace one operation to the bulk operation
  654. *
  655. * @method
  656. * @param {object} replacement the new document to replace the existing one with
  657. * @throws {MongoError} If operation cannot be added to bulk write
  658. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  659. */
  660. replaceOne(replacement) {
  661. // Perform upsert
  662. const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
  663. // Establish the update command
  664. const document = {
  665. q: this.s.currentOp.selector,
  666. u: replacement,
  667. multi: false,
  668. upsert: upsert
  669. };
  670. if (replacement.hint) {
  671. document.hint = replacement.hint;
  672. }
  673. if (hasAtomicOperators(replacement)) {
  674. throw new TypeError('Replacement document must not use atomic operators');
  675. }
  676. // Clear out current Op
  677. this.s.currentOp = null;
  678. return this.s.options.addToOperationsList(this, UPDATE, document);
  679. }
  680. /**
  681. * Upsert modifier for update bulk operation, noting that this operation is an upsert.
  682. *
  683. * @method
  684. * @throws {MongoError} If operation cannot be added to bulk write
  685. * @return {FindOperators} reference to self
  686. */
  687. upsert() {
  688. this.s.currentOp.upsert = true;
  689. return this;
  690. }
  691. /**
  692. * Add a delete one operation to the bulk operation
  693. *
  694. * @method
  695. * @throws {MongoError} If operation cannot be added to bulk write
  696. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  697. */
  698. deleteOne() {
  699. // Establish the update command
  700. const document = {
  701. q: this.s.currentOp.selector,
  702. limit: 1
  703. };
  704. // Clear out current Op
  705. this.s.currentOp = null;
  706. return this.s.options.addToOperationsList(this, REMOVE, document);
  707. }
  708. /**
  709. * Add a delete many operation to the bulk operation
  710. *
  711. * @method
  712. * @throws {MongoError} If operation cannot be added to bulk write
  713. * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
  714. */
  715. delete() {
  716. // Establish the update command
  717. const document = {
  718. q: this.s.currentOp.selector,
  719. limit: 0
  720. };
  721. // Clear out current Op
  722. this.s.currentOp = null;
  723. return this.s.options.addToOperationsList(this, REMOVE, document);
  724. }
  725. /**
  726. * backwards compatability for deleteOne
  727. * @deprecated
  728. */
  729. removeOne() {
  730. emitWarningOnce('bulk operation `removeOne` has been deprecated, please use `deleteOne`');
  731. return this.deleteOne();
  732. }
  733. /**
  734. * backwards compatability for delete
  735. * @deprecated
  736. */
  737. remove() {
  738. emitWarningOnce('bulk operation `remove` has been deprecated, please use `delete`');
  739. return this.delete();
  740. }
  741. }
  742. /**
  743. * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation
  744. *
  745. * **NOTE:** Internal Type, do not instantiate directly
  746. */
  747. class BulkOperationBase {
  748. /**
  749. * Create a new OrderedBulkOperation or UnorderedBulkOperation instance
  750. * @property {number} length Get the number of operations in the bulk.
  751. */
  752. constructor(topology, collection, options, isOrdered) {
  753. // determine whether bulkOperation is ordered or unordered
  754. this.isOrdered = isOrdered;
  755. options = options == null ? {} : options;
  756. // TODO Bring from driver information in isMaster
  757. // Get the namespace for the write operations
  758. const namespace = collection.s.namespace;
  759. // Used to mark operation as executed
  760. const executed = false;
  761. // Current item
  762. const currentOp = null;
  763. // Handle to the bson serializer, used to calculate running sizes
  764. const bson = topology.bson;
  765. // Set max byte size
  766. const isMaster = topology.lastIsMaster();
  767. // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents
  768. // over 2mb are still allowed
  769. const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);
  770. const maxBsonObjectSize =
  771. isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16;
  772. const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;
  773. const maxWriteBatchSize =
  774. isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000;
  775. // Calculates the largest possible size of an Array key, represented as a BSON string
  776. // element. This calculation:
  777. // 1 byte for BSON type
  778. // # of bytes = length of (string representation of (maxWriteBatchSize - 1))
  779. // + 1 bytes for null terminator
  780. const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
  781. // Final options for retryable writes and write concern
  782. let finalOptions = Object.assign({}, options);
  783. finalOptions = applyRetryableWrites(finalOptions, collection.s.db);
  784. finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options);
  785. const writeConcern = finalOptions.writeConcern;
  786. // Get the promiseLibrary
  787. const promiseLibrary = options.promiseLibrary || Promise;
  788. // Final results
  789. const bulkResult = {
  790. ok: 1,
  791. writeErrors: [],
  792. writeConcernErrors: [],
  793. insertedIds: [],
  794. nInserted: 0,
  795. nUpserted: 0,
  796. nMatched: 0,
  797. nModified: 0,
  798. nRemoved: 0,
  799. upserted: []
  800. };
  801. // Internal state
  802. this.s = {
  803. // Final result
  804. bulkResult: bulkResult,
  805. // Current batch state
  806. currentBatch: null,
  807. currentIndex: 0,
  808. // ordered specific
  809. currentBatchSize: 0,
  810. currentBatchSizeBytes: 0,
  811. // unordered specific
  812. currentInsertBatch: null,
  813. currentUpdateBatch: null,
  814. currentRemoveBatch: null,
  815. batches: [],
  816. // Write concern
  817. writeConcern: writeConcern,
  818. // Max batch size options
  819. maxBsonObjectSize,
  820. maxBatchSizeBytes,
  821. maxWriteBatchSize,
  822. maxKeySize,
  823. // Namespace
  824. namespace: namespace,
  825. // BSON
  826. bson: bson,
  827. // Topology
  828. topology: topology,
  829. // Options
  830. options: finalOptions,
  831. // Current operation
  832. currentOp: currentOp,
  833. // Executed
  834. executed: executed,
  835. // Collection
  836. collection: collection,
  837. // Promise Library
  838. promiseLibrary: promiseLibrary,
  839. // Fundamental error
  840. err: null,
  841. // check keys
  842. checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true
  843. };
  844. // bypass Validation
  845. if (options.bypassDocumentValidation === true) {
  846. this.s.bypassDocumentValidation = true;
  847. }
  848. }
  849. /**
  850. * Add a single insert document to the bulk operation
  851. *
  852. * @param {object} document the document to insert
  853. * @throws {MongoError}
  854. * @return {BulkOperationBase} A reference to self
  855. *
  856. * @example
  857. * const bulkOp = collection.initializeOrderedBulkOp();
  858. * // Adds three inserts to the bulkOp.
  859. * bulkOp
  860. * .insert({ a: 1 })
  861. * .insert({ b: 2 })
  862. * .insert({ c: 3 });
  863. * await bulkOp.execute();
  864. */
  865. insert(document) {
  866. if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null)
  867. document._id = new ObjectID();
  868. return this.s.options.addToOperationsList(this, INSERT, document);
  869. }
  870. /**
  871. * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
  872. * Returns a builder object used to complete the definition of the operation.
  873. *
  874. * @method
  875. * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation}
  876. * @throws {MongoError} if a selector is not specified
  877. * @return {FindOperators} A helper object with which the write operation can be defined.
  878. *
  879. * @example
  880. * const bulkOp = collection.initializeOrderedBulkOp();
  881. *
  882. * // Add an updateOne to the bulkOp
  883. * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
  884. *
  885. * // Add an updateMany to the bulkOp
  886. * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
  887. *
  888. * // Add an upsert
  889. * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
  890. *
  891. * // Add a deletion
  892. * bulkOp.find({ g: 7 }).deleteOne();
  893. *
  894. * // Add a multi deletion
  895. * bulkOp.find({ h: 8 }).delete();
  896. *
  897. * // Add a replaceOne
  898. * bulkOp.find({ i: 9 }).replaceOne({ j: 10 });
  899. *
  900. * // Update using a pipeline (requires Mongodb 4.2 or higher)
  901. * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
  902. * { $set: { total: { $sum: [ '$y', '$z' ] } } }
  903. * ]);
  904. *
  905. * // All of the ops will now be executed
  906. * await bulkOp.execute();
  907. */
  908. find(selector) {
  909. if (!selector) {
  910. throw toError('Bulk find operation must specify a selector');
  911. }
  912. // Save a current selector
  913. this.s.currentOp = {
  914. selector: selector
  915. };
  916. return new FindOperators(this);
  917. }
  918. /**
  919. * Specifies a raw operation to perform in the bulk write.
  920. *
  921. * @method
  922. * @param {object} op The raw operation to perform.
  923. * @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.
  924. * @return {BulkOperationBase} A reference to self
  925. */
  926. raw(op) {
  927. const key = Object.keys(op)[0];
  928. // Set up the force server object id
  929. const forceServerObjectId =
  930. typeof this.s.options.forceServerObjectId === 'boolean'
  931. ? this.s.options.forceServerObjectId
  932. : this.s.collection.s.db.options.forceServerObjectId;
  933. // Update operations
  934. if (
  935. (op.updateOne && op.updateOne.q) ||
  936. (op.updateMany && op.updateMany.q) ||
  937. (op.replaceOne && op.replaceOne.q)
  938. ) {
  939. op[key].multi = op.updateOne || op.replaceOne ? false : true;
  940. return this.s.options.addToOperationsList(this, UPDATE, op[key]);
  941. }
  942. // Crud spec update format
  943. if (op.updateOne || op.updateMany || op.replaceOne) {
  944. if (op.replaceOne && hasAtomicOperators(op[key].replacement)) {
  945. throw new TypeError('Replacement document must not use atomic operators');
  946. } else if ((op.updateOne || op.updateMany) && !hasAtomicOperators(op[key].update)) {
  947. throw new TypeError('Update document requires atomic operators');
  948. }
  949. const multi = op.updateOne || op.replaceOne ? false : true;
  950. const operation = {
  951. q: op[key].filter,
  952. u: op[key].update || op[key].replacement,
  953. multi: multi
  954. };
  955. if (op[key].hint) {
  956. operation.hint = op[key].hint;
  957. }
  958. if (this.isOrdered) {
  959. operation.upsert = op[key].upsert ? true : false;
  960. if (op.collation) operation.collation = op.collation;
  961. } else {
  962. if (op[key].upsert) operation.upsert = true;
  963. }
  964. if (op[key].arrayFilters) {
  965. // TODO: this check should be done at command construction against a connection, not a topology
  966. if (maxWireVersion(this.s.topology) < 6) {
  967. throw new TypeError('arrayFilters are only supported on MongoDB 3.6+');
  968. }
  969. operation.arrayFilters = op[key].arrayFilters;
  970. }
  971. return this.s.options.addToOperationsList(this, UPDATE, operation);
  972. }
  973. // Remove operations
  974. if (
  975. op.removeOne ||
  976. op.removeMany ||
  977. (op.deleteOne && op.deleteOne.q) ||
  978. (op.deleteMany && op.deleteMany.q)
  979. ) {
  980. op[key].limit = op.removeOne ? 1 : 0;
  981. return this.s.options.addToOperationsList(this, REMOVE, op[key]);
  982. }
  983. // Crud spec delete operations, less efficient
  984. if (op.deleteOne || op.deleteMany) {
  985. const limit = op.deleteOne ? 1 : 0;
  986. const operation = { q: op[key].filter, limit: limit };
  987. if (op[key].hint) {
  988. operation.hint = op[key].hint;
  989. }
  990. if (this.isOrdered) {
  991. if (op.collation) operation.collation = op.collation;
  992. }
  993. return this.s.options.addToOperationsList(this, REMOVE, operation);
  994. }
  995. // Insert operations
  996. if (op.insertOne && op.insertOne.document == null) {
  997. if (forceServerObjectId !== true && op.insertOne._id == null)
  998. op.insertOne._id = new ObjectID();
  999. return this.s.options.addToOperationsList(this, INSERT, op.insertOne);
  1000. } else if (op.insertOne && op.insertOne.document) {
  1001. if (forceServerObjectId !== true && op.insertOne.document._id == null)
  1002. op.insertOne.document._id = new ObjectID();
  1003. return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document);
  1004. }
  1005. if (op.insertMany) {
  1006. emitWarningOnce(
  1007. 'bulk operation `insertMany` has been deprecated; use multiple `insertOne` ops instead'
  1008. );
  1009. for (let i = 0; i < op.insertMany.length; i++) {
  1010. if (forceServerObjectId !== true && op.insertMany[i]._id == null)
  1011. op.insertMany[i]._id = new ObjectID();
  1012. this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]);
  1013. }
  1014. return;
  1015. }
  1016. // No valid type of operation
  1017. throw toError(
  1018. 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'
  1019. );
  1020. }
  1021. /**
  1022. * helper function to assist with promiseOrCallback behavior
  1023. * @ignore
  1024. * @param {*} err
  1025. * @param {*} callback
  1026. */
  1027. _handleEarlyError(err, callback) {
  1028. if (typeof callback === 'function') {
  1029. callback(err, null);
  1030. return;
  1031. }
  1032. return this.s.promiseLibrary.reject(err);
  1033. }
  1034. /**
  1035. * An internal helper method. Do not invoke directly. Will be going away in the future
  1036. *
  1037. * @ignore
  1038. * @method
  1039. * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation
  1040. * @param {object} writeConcern
  1041. * @param {object} options
  1042. * @param {function} callback
  1043. */
  1044. bulkExecute(_writeConcern, options, callback) {
  1045. if (typeof options === 'function') (callback = options), (options = {});
  1046. options = options || {};
  1047. if (typeof _writeConcern === 'function') {
  1048. callback = _writeConcern;
  1049. } else if (_writeConcern && typeof _writeConcern === 'object') {
  1050. this.s.writeConcern = _writeConcern;
  1051. }
  1052. if (this.s.executed) {
  1053. const executedError = toError('batch cannot be re-executed');
  1054. return this._handleEarlyError(executedError, callback);
  1055. }
  1056. // If we have current batch
  1057. if (this.isOrdered) {
  1058. if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
  1059. } else {
  1060. if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
  1061. if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
  1062. if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
  1063. }
  1064. // If we have no operations in the bulk raise an error
  1065. if (this.s.batches.length === 0) {
  1066. const emptyBatchError = toError('Invalid Operation, no operations specified');
  1067. return this._handleEarlyError(emptyBatchError, callback);
  1068. }
  1069. return { options, callback };
  1070. }
  1071. /**
  1072. * The callback format for results
  1073. * @callback BulkOperationBase~resultCallback
  1074. * @param {MongoError} error An error instance representing the error during the execution.
  1075. * @param {BulkWriteResult} result The bulk write result.
  1076. */
  1077. /**
  1078. * Execute the bulk operation
  1079. *
  1080. * @method
  1081. * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options.
  1082. * @param {object} [options] Optional settings.
  1083. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1084. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1085. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1086. * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead.
  1087. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1088. * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors
  1089. * @throws {MongoError} Throws error if the bulk object has already been executed
  1090. * @throws {MongoError} Throws error if the bulk object does not have any operations
  1091. * @return {Promise|void} returns Promise if no callback passed
  1092. */
  1093. execute(_writeConcern, options, callback) {
  1094. const ret = this.bulkExecute(_writeConcern, options, callback);
  1095. if (!ret || isPromiseLike(ret)) {
  1096. return ret;
  1097. }
  1098. options = ret.options;
  1099. callback = ret.callback;
  1100. return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);
  1101. }
  1102. /**
  1103. * Handles final options before executing command
  1104. *
  1105. * An internal method. Do not invoke. Will not be accessible in the future
  1106. *
  1107. * @ignore
  1108. * @param {object} config
  1109. * @param {object} config.options
  1110. * @param {number} config.batch
  1111. * @param {function} config.resultHandler
  1112. * @param {function} callback
  1113. */
  1114. finalOptionsHandler(config, callback) {
  1115. const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options);
  1116. if (this.s.writeConcern != null) {
  1117. finalOptions.writeConcern = this.s.writeConcern;
  1118. }
  1119. if (finalOptions.bypassDocumentValidation !== true) {
  1120. delete finalOptions.bypassDocumentValidation;
  1121. }
  1122. // Set an operationIf if provided
  1123. if (this.operationId) {
  1124. config.resultHandler.operationId = this.operationId;
  1125. }
  1126. // Serialize functions
  1127. if (this.s.options.serializeFunctions) {
  1128. finalOptions.serializeFunctions = true;
  1129. }
  1130. // Ignore undefined
  1131. if (this.s.options.ignoreUndefined) {
  1132. finalOptions.ignoreUndefined = true;
  1133. }
  1134. // Is the bypassDocumentValidation options specific
  1135. if (this.s.bypassDocumentValidation === true) {
  1136. finalOptions.bypassDocumentValidation = true;
  1137. }
  1138. // Is the checkKeys option disabled
  1139. if (this.s.checkKeys === false) {
  1140. finalOptions.checkKeys = false;
  1141. }
  1142. if (finalOptions.retryWrites) {
  1143. if (config.batch.batchType === UPDATE) {
  1144. finalOptions.retryWrites =
  1145. finalOptions.retryWrites && !config.batch.operations.some(op => op.multi);
  1146. }
  1147. if (config.batch.batchType === REMOVE) {
  1148. finalOptions.retryWrites =
  1149. finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0);
  1150. }
  1151. }
  1152. try {
  1153. if (config.batch.batchType === INSERT) {
  1154. this.s.topology.insert(
  1155. this.s.namespace,
  1156. config.batch.operations,
  1157. finalOptions,
  1158. config.resultHandler
  1159. );
  1160. } else if (config.batch.batchType === UPDATE) {
  1161. this.s.topology.update(
  1162. this.s.namespace,
  1163. config.batch.operations,
  1164. finalOptions,
  1165. config.resultHandler
  1166. );
  1167. } else if (config.batch.batchType === REMOVE) {
  1168. this.s.topology.remove(
  1169. this.s.namespace,
  1170. config.batch.operations,
  1171. finalOptions,
  1172. config.resultHandler
  1173. );
  1174. }
  1175. } catch (err) {
  1176. // Force top level error
  1177. err.ok = 0;
  1178. // Merge top level error and return
  1179. handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null));
  1180. }
  1181. }
  1182. /**
  1183. * Handles the write error before executing commands
  1184. *
  1185. * An internal helper method. Do not invoke directly. Will be going away in the future
  1186. *
  1187. * @ignore
  1188. * @param {function} callback
  1189. * @param {BulkWriteResult} writeResult
  1190. * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation
  1191. */
  1192. handleWriteError(callback, writeResult) {
  1193. if (this.s.bulkResult.writeErrors.length > 0) {
  1194. const msg = this.s.bulkResult.writeErrors[0].errmsg
  1195. ? this.s.bulkResult.writeErrors[0].errmsg
  1196. : 'write operation failed';
  1197. handleCallback(
  1198. callback,
  1199. new BulkWriteError(
  1200. toError({
  1201. message: msg,
  1202. code: this.s.bulkResult.writeErrors[0].code,
  1203. writeErrors: this.s.bulkResult.writeErrors
  1204. }),
  1205. writeResult
  1206. ),
  1207. null
  1208. );
  1209. return true;
  1210. }
  1211. if (writeResult.getWriteConcernError()) {
  1212. handleCallback(
  1213. callback,
  1214. new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult),
  1215. null
  1216. );
  1217. return true;
  1218. }
  1219. }
  1220. }
  1221. Object.defineProperty(BulkOperationBase.prototype, 'length', {
  1222. enumerable: true,
  1223. get: function() {
  1224. return this.s.currentIndex;
  1225. }
  1226. });
  1227. // Exports symbols
  1228. module.exports = {
  1229. Batch,
  1230. BulkOperationBase,
  1231. bson,
  1232. INSERT: INSERT,
  1233. UPDATE: UPDATE,
  1234. REMOVE: REMOVE,
  1235. BulkWriteError,
  1236. BulkWriteResult
  1237. };