7

I can not rename a collection in mongoDB. I can see that it exists and can write and read data from it. I have attempted the following using the node mongo native driver.

db.collection("mycollection").renameCollection("mynewcollection");

error: TypeError: Object #<Collection> has no method 'renameCollection'

and

db['mycollection'].renameCollection("mynewcollection");

Cannot call method 'renameCollection' of undefined

performing the following in the same place returns all docs as expected

db.collection("mycollection").find({}).toArray(function(err, docs){
    console.log(docs);
});
christian
  • 110
  • 1
  • 2
  • 15
wazzaday
  • 9,474
  • 6
  • 39
  • 66
  • Have you tried `db.mycollection.renameCollection("mynewcollection");`?[Manual](http://docs.mongodb.org/manual/reference/method/db.collection.renameCollection/) – chridam Feb 02 '15 at 15:21
  • yeah, it is the same as the first solution but I have still tried both syntax's – wazzaday Feb 02 '15 at 15:26
  • I think you need the `rename` [method](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#rename) – chridam Feb 02 '15 at 15:32

2 Answers2

21

The method to rename a collection using the node.js driver is rename, not renameCollection:

db.collection("mycollection").rename("mynewcollection", function(err, newColl) {...});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 2
    @wazzaday For what it's worth, they named it that way because the dot chaining syntax already puts you in the context of a collection. It's easier in plain English to read "collection.rename", but more redundant to read "collection.renameCollection". They tried to make the API more intuitive that way. – CatDadCode Feb 02 '15 at 16:34
0

add this code to your collection.js (it should be added to line 153, or endof the collection.js code) , it should resolve the problem.

req.collection.rename(name, function(err, collection) {
     if (err) {
-      req.session.error('Something went wrong: ' + err);
+      req.session.error = 'Something went wrong: ' + err;
       console.error(err);
       return res.redirect('back');
     }

     req.updateCollections(req.db, req.dbName, function(err) {
       if (err) {
-        req.session.error('Something went wrong: ' + err);
+        req.session.error = 'Something went wrong: ' + err;
         return res.redirect('back');
       }

-      req.session.success('Collection renamed!');
+      req.session.success = 'Collection renamed!';
       res.redirect(config.site.baseUrl+'db/' + req.dbName + '/' + name);
     });
   });
user 12321
  • 2,846
  • 1
  • 24
  • 34