1

How do I use renameCollection with Meteor? I would like to do this inside Meteor because I need do migrations for development and production environment.

Charles Han
  • 772
  • 1
  • 8
  • 21
  • You can use the Node.js MongoDB driver, but I assume that there will be side effects when used on a running Meteor server (with OpLog tailing and reactivity). What are you trying to accomplish? – MasterAM Feb 02 '16 at 21:27
  • 1
    Possible duplicate of [How to rename a collection in meteor?](http://stackoverflow.com/questions/29070599/how-to-rename-a-collection-in-meteor) – Stephen Woods Feb 02 '16 at 21:48

1 Answers1

0

Use the RemoteCollectionDriver to access the native mongo driver and the instance administraion commands, including the renameCollection command.

The following example renames a collection named orders in the test database to orders2016 in the test database:

var mongoDriver = MongoInternals.defaultRemoteCollectionDriver(), // or Meteor._RemoteCollectionDriver
    db = mongoDriver.mongo.db;

// for commands not natively supported by the driver - https://docs.mongodb.org/manual/reference/command/
db.command({ renameCollection: "test.orders", to: "test.orders2016" }, function(error, result) {
    if (error) throw error;
    if (result.errmsg) {
        console.error('Error calling native renameCollection command:', result.errmsg);
    }
    else {
        console.log(result);
    }
});

To implement this server side, you could follow this asynchronous pattern:

var shell = function () {
    var Future = Npm.require('fibers/future'),
        future = new Future(),
        db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    db.command({ renameCollection: "test.orders", to: "test.orders2016" }, 
        function(error, result) {
            if (err) throw new Meteor.Error(500, "failed");
            future.return(result);
        }
    );
    return future.wait();
};
chridam
  • 100,957
  • 23
  • 236
  • 235