summaryrefslogtreecommitdiffstats
path: root/node_modules/mongodb/lib/operations/rename.js
blob: 8098fe6be5f2a787da3db42bd656f72ab8b8814a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';

const OperationBase = require('./operation').OperationBase;
const applyWriteConcern = require('../utils').applyWriteConcern;
const checkCollectionName = require('../utils').checkCollectionName;
const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand;
const handleCallback = require('../utils').handleCallback;
const loadCollection = require('../dynamic_loaders').loadCollection;
const toError = require('../utils').toError;

class RenameOperation extends OperationBase {
  constructor(collection, newName, options) {
    super(options);

    this.collection = collection;
    this.newName = newName;
  }

  execute(callback) {
    const coll = this.collection;
    const newName = this.newName;
    const options = this.options;

    let Collection = loadCollection();
    // Check the collection name
    checkCollectionName(newName);
    // Build the command
    const renameCollection = coll.namespace;
    const toCollection = coll.s.namespace.withCollection(newName).toString();
    const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;
    const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };

    // Decorate command with writeConcern if supported
    applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options);

    // Execute against admin
    executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => {
      if (err) return handleCallback(callback, err, null);
      // We have an error
      if (doc.errmsg) return handleCallback(callback, toError(doc), null);
      try {
        return handleCallback(
          callback,
          null,
          new Collection(
            coll.s.db,
            coll.s.topology,
            coll.s.namespace.db,
            newName,
            coll.s.pkFactory,
            coll.s.options
          )
        );
      } catch (err) {
        return handleCallback(callback, toError(err), null);
      }
    });
  }
}

module.exports = RenameOperation;