2017-04-13 208 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。 –