create_indexes.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const Aspect = require('./operation').Aspect;
  3. const defineAspects = require('./operation').defineAspects;
  4. const OperationBase = require('./operation').OperationBase;
  5. const executeCommand = require('./db_ops').executeCommand;
  6. const MongoError = require('../core').MongoError;
  7. const ReadPreference = require('../core').ReadPreference;
  8. class CreateIndexesOperation extends OperationBase {
  9. constructor(collection, indexSpecs, options) {
  10. super(options);
  11. this.collection = collection;
  12. this.indexSpecs = indexSpecs;
  13. }
  14. execute(callback) {
  15. const coll = this.collection;
  16. const indexSpecs = this.indexSpecs;
  17. let options = this.options;
  18. const capabilities = coll.s.topology.capabilities();
  19. // Ensure we generate the correct name if the parameter is not set
  20. for (let i = 0; i < indexSpecs.length; i++) {
  21. if (indexSpecs[i].name == null) {
  22. const keys = [];
  23. // Did the user pass in a collation, check if our write server supports it
  24. if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {
  25. return callback(new MongoError('server/primary/mongos does not support collation'));
  26. }
  27. for (let name in indexSpecs[i].key) {
  28. keys.push(`${name}_${indexSpecs[i].key[name]}`);
  29. }
  30. // Set the name
  31. indexSpecs[i].name = keys.join('_');
  32. }
  33. }
  34. options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
  35. // Execute the index
  36. executeCommand(
  37. coll.s.db,
  38. {
  39. createIndexes: coll.collectionName,
  40. indexes: indexSpecs
  41. },
  42. options,
  43. callback
  44. );
  45. }
  46. }
  47. defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION);
  48. module.exports = CreateIndexesOperation;