我需要用大约8000万条记录填充Mongo集合,例如
//Example
{
"_id" : "4gtvCPATZ",
"isActivated" : false
}
其中_id是随机生成的。我使用Node.js Express和Mongoose执行此操作:
app.get('/api/codes', function(req, res) {
for (var i = 0; i < 100000; i++) {
var code = new Code({
_id: randomStr(9),
isActivated: 0
});
code.save();
code = null;
}
res.render('index');
});
function randomStr(m) {
var m = m || 9;
s = '', r = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz123456789';
for (var i = 0; i < m; i++) {
s += r.charAt(Math.floor(Math.random() * r.length));
}
return s;
};
在'index'上,jade布局有JS代码重新加载页面以生成下一个100000条记录:
script(type='text/javascript').
location.href='http://localhost:3000/api/codes'
node.js进程开始消耗内存,4-5页重新加载后挂起1GB内存。
我做错了什么?
更新: 考虑到robertklep的评论,我已经更新了代码并且它正常工作:
app.get('/api/codes', function(req, res) {
var count = 0;
async.whilst(
function () { return count < 100000; },
function (callback) {
count++;
var code = new Code({
_id: randomStr(9),
isActivated: 0
});
code.save(function(){
callback();
});
},
function (err) {
res.render('index');
}
);
});
更新2 :我测试了怪异的建议并让我的应用更快地运行:
var MongoDB = require("mongodb");
app.get('/api/codes', function(req, res) {
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/code', function(err, db) {
var collection = db.collection('codes');
var count = 0;
async.whilst(
function () { return count < 10; },
function (callback) {
count++;
var docs = [];
for (var i = 0; i < 100000; i++) {
docs.push({
_id: randomStr(9),
isActivated: 0
});
}
collection.insert(docs, function(err, docs) {
callback();
});
},
function (err) {
res.render('index');
}
);
})
});
现在它在60-70秒内写下大约1M条记录。
谢谢!