【发布时间】:2019-03-21 00:48:59
【问题描述】:
我正在尝试将我的数据库移动到另一台服务器。
我有 410k~ 个文档的集合,我想将它们部分 100 x 100 移动到带有 mongodb 数据库的新服务器。
有我的代码:
var mongoose = require('mongoose');
var itemdataModel = require('./model/ItemData');
mongoose.connection.on('error', function(err) {
console.log('MongoDB Connection Error.' + err);
process.exit(1);
});
mongoose.connection.on('close', function() {
console.log('Connection closed');
process.exit(1);
});
const ins = async (itemz) => {
try {
console.log("Inserting..")
await mongoose.connect('<url to new database>', { useNewUrlParser: true });
await gamedataModel.insertMany(itemz,
async (err, result) => {
if (err) {
console.log("Insert query error" + err)
await mongoose.connection.close()
} else {
console.log("Inserted!");
await mongoose.connection.close()
}
});
} catch (e) {
console.log('insert error ' + e)
}
}
(async () => {
mongoose.connect('<url to old database>', { useNewUrlParser: true });
const wyn = await itemdataModel.find({}).countDocuments()
console.log('Documents count: ' + wyn)
for (let i = 0; i < wyn; i += 100) {
const docs = await itemdataModel.find({status: 'processed'}, '', {'skip': i, 'limit': 100 }).lean().exec()
console.log('Selected ' + docs.length + ' documents to move')
await mongoose.connection.close()
await ins(docs)
}
})();
在“ins”函数中连接第二个数据库有问题,有我的控制台输出:
文档数:411975
选择了 100 个要移动的文档
连接关闭
如何让它工作? 需要先关闭第一个连接,然后再开始另一个连接以插入 100 个文档,然后关闭它并返回我的循环以移动另外 100 个文档?
我不想通过同时在两个服务器上打开 411k/100 个连接来使服务器过载
【问题讨论】:
标签: javascript node.js database mongoose