insert_many.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const OperationBase = require('./operation').OperationBase;
  3. const BulkWriteOperation = require('./bulk_write');
  4. const MongoError = require('../core').MongoError;
  5. const prepareDocs = require('./common_functions').prepareDocs;
  6. class InsertManyOperation extends OperationBase {
  7. constructor(collection, docs, options) {
  8. super(options);
  9. this.collection = collection;
  10. this.docs = docs;
  11. }
  12. execute(callback) {
  13. const coll = this.collection;
  14. let docs = this.docs;
  15. const options = this.options;
  16. if (!Array.isArray(docs)) {
  17. return callback(
  18. MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })
  19. );
  20. }
  21. // If keep going set unordered
  22. options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions;
  23. docs = prepareDocs(coll, docs, options);
  24. // Generate the bulk write operations
  25. const operations = [
  26. {
  27. insertMany: docs
  28. }
  29. ];
  30. const bulkWriteOperation = new BulkWriteOperation(coll, operations, options);
  31. bulkWriteOperation.execute((err, result) => {
  32. if (err) return callback(err, null);
  33. callback(null, mapInsertManyResults(docs, result));
  34. });
  35. }
  36. }
  37. function mapInsertManyResults(docs, r) {
  38. const finalResult = {
  39. result: { ok: 1, n: r.insertedCount },
  40. ops: docs,
  41. insertedCount: r.insertedCount,
  42. insertedIds: r.insertedIds
  43. };
  44. if (r.getLastOp()) {
  45. finalResult.result.opTime = r.getLastOp();
  46. }
  47. return finalResult;
  48. }
  49. module.exports = InsertManyOperation;