Mongoose rename collection

我们两清 提交于 2021-02-09 07:15:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/43391592/mongoose-rename-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!