insert_many.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 = docs.map(document => ({ insertOne: { document } }));
  26. const bulkWriteOperation = new BulkWriteOperation(coll, operations, options);
  27. bulkWriteOperation.execute((err, result) => {
  28. if (err) return callback(err, null);
  29. callback(null, mapInsertManyResults(docs, result));
  30. });
  31. }
  32. }
  33. function mapInsertManyResults(docs, r) {
  34. const finalResult = {
  35. result: { ok: 1, n: r.insertedCount },
  36. ops: docs,
  37. insertedCount: r.insertedCount,
  38. insertedIds: r.insertedIds
  39. };
  40. if (r.getLastOp()) {
  41. finalResult.result.opTime = r.getLastOp();
  42. }
  43. return finalResult;
  44. }
  45. module.exports = InsertManyOperation;