2017-04-13 90 views
1

我試圖使貓鼬db.collection.renameCollection,但我無法在任何地方找到該功能。他們錯過了添加它還是我看錯了地方?
的我在做什麼作爲簡單的例子是:貓鼬重命名集合

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

這表明未定義。

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

這也給出了未定義。

+0

格式應該是'db.collectionName.renameCollection( 「NewCollectionName」)'你不及格新的集合名稱。如果您希望函數能夠正常工作,則需要傳遞正確的參數 –

+0

即使在集合變量中它也很難實現。我將在幾分鐘內編輯帖子並添加對您的評論的答案。 –

回答

2

下面是一個使用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('foobar').rename('test'); 
}).then(() => { 
    console.log('rename successful'); 
}).catch(e => { 
    console.log('rename failed:', e.message); 
}).then(() => { 
    console.log('disconnecting'); 
    mongoose.disconnect(); 
}); 

正如你所看到的,MongoDB的驅動程序公開的renameCollection()方法rename(),這是記錄在這裏:http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#rename

+0

這看起來工作,但我需要測試它,我會在1小時回覆。 –

+0

'.rename('test')'做了詭計,我正在尋找collectionRename。 –