bulk_write.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. const applyRetryableWrites = require('../utils').applyRetryableWrites;
  3. const applyWriteConcern = require('../utils').applyWriteConcern;
  4. const MongoError = require('../core').MongoError;
  5. const OperationBase = require('./operation').OperationBase;
  6. class BulkWriteOperation extends OperationBase {
  7. constructor(collection, operations, options) {
  8. super(options);
  9. this.collection = collection;
  10. this.operations = operations;
  11. }
  12. execute(callback) {
  13. const coll = this.collection;
  14. const operations = this.operations;
  15. let options = this.options;
  16. // Add ignoreUndfined
  17. if (coll.s.options.ignoreUndefined) {
  18. options = Object.assign({}, options);
  19. options.ignoreUndefined = coll.s.options.ignoreUndefined;
  20. }
  21. // Create the bulk operation
  22. const bulk =
  23. options.ordered === true || options.ordered == null
  24. ? coll.initializeOrderedBulkOp(options)
  25. : coll.initializeUnorderedBulkOp(options);
  26. // Do we have a collation
  27. let collation = false;
  28. // for each op go through and add to the bulk
  29. try {
  30. for (let i = 0; i < operations.length; i++) {
  31. // Get the operation type
  32. const key = Object.keys(operations[i])[0];
  33. // Check if we have a collation
  34. if (operations[i][key].collation) {
  35. collation = true;
  36. }
  37. // Pass to the raw bulk
  38. bulk.raw(operations[i]);
  39. }
  40. } catch (err) {
  41. return callback(err, null);
  42. }
  43. // Final options for retryable writes and write concern
  44. let finalOptions = Object.assign({}, options);
  45. finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
  46. finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
  47. const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
  48. const capabilities = coll.s.topology.capabilities();
  49. // Did the user pass in a collation, check if our write server supports it
  50. if (collation && capabilities && !capabilities.commandsTakeCollation) {
  51. return callback(new MongoError('server/primary/mongos does not support collation'));
  52. }
  53. // Execute the bulk
  54. bulk.execute(writeCon, finalOptions, (err, r) => {
  55. // We have connection level error
  56. if (!r && err) {
  57. return callback(err, null);
  58. }
  59. // Return the results
  60. callback(null, r);
  61. });
  62. }
  63. }
  64. module.exports = BulkWriteOperation;