Node.js + Mongoose消耗插入的所有内存

我需要填写大约8000万条logging

//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; }; 

在“索引”中,玉石版面有JS代码,重新载入页面生成下一个100000条logging:

 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 :我已经testing了怪异的build议,并使我的应用程序工作更快:

 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个logging。

谢谢!