Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose rename collection

I am trying to make db.collection.renameCollection with mongoose, but i can't find that function anywhere. Did they miss to add it or i am looking at wrong place?
As quick example of what i am doing is:

var conn = mongoose.createConnection('localhost',"dbname");
var Collection = conn.model(collectionName, Schema, collectionName);
console.log(typeof Collection.renameCollection);

Which show undefined.

var con = mongoose.createConnection('localhost',"dbname");
con.once('open', function() {
    console.log(typeof con.db[obj.name]);
});

This give also undefined.

like image 793
Honchar Denys Avatar asked Jan 05 '23 04:01

Honchar Denys


1 Answers

Here's an example that will perform a rename operation using Mongoose.

const mongoose   = require('mongoose');
mongoose.Promise = Promise;

mongoose.connect('mongodb://localhost/test').then(() => {
  console.log('connected');

  // Access the underlying database object provided by the MongoDB driver.
  let db = mongoose.connection.db;

  // Rename the `test` collection to `foobar`
  return db.collection('test').rename('foobar');
}).then(() => {
  console.log('rename successful');
}).catch(e => {
  console.log('rename failed:', e.message);
}).then(() => {
  console.log('disconnecting');
  mongoose.disconnect();
});

As you can see, the MongoDB driver exposes the renameCollection() method as rename(), which is documented here: http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#rename

like image 66
robertklep Avatar answered Jan 12 '23 01:01

robertklep