rename.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const OperationBase = require('./operation').OperationBase;
  3. const applyWriteConcern = require('../utils').applyWriteConcern;
  4. const checkCollectionName = require('../utils').checkCollectionName;
  5. const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand;
  6. const handleCallback = require('../utils').handleCallback;
  7. const loadCollection = require('../dynamic_loaders').loadCollection;
  8. const toError = require('../utils').toError;
  9. class RenameOperation extends OperationBase {
  10. constructor(collection, newName, options) {
  11. super(options);
  12. this.collection = collection;
  13. this.newName = newName;
  14. }
  15. execute(callback) {
  16. const coll = this.collection;
  17. const newName = this.newName;
  18. const options = this.options;
  19. let Collection = loadCollection();
  20. // Check the collection name
  21. checkCollectionName(newName);
  22. // Build the command
  23. const renameCollection = coll.namespace;
  24. const toCollection = coll.s.namespace.withCollection(newName).toString();
  25. const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;
  26. const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };
  27. // Decorate command with writeConcern if supported
  28. applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options);
  29. // Execute against admin
  30. executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => {
  31. if (err) return handleCallback(callback, err, null);
  32. // We have an error
  33. if (doc.errmsg) return handleCallback(callback, toError(doc), null);
  34. try {
  35. return handleCallback(
  36. callback,
  37. null,
  38. new Collection(
  39. coll.s.db,
  40. coll.s.topology,
  41. coll.s.namespace.db,
  42. newName,
  43. coll.s.pkFactory,
  44. coll.s.options
  45. )
  46. );
  47. } catch (err) {
  48. return handleCallback(callback, toError(err), null);
  49. }
  50. });
  51. }
  52. }
  53. module.exports = RenameOperation;