【发布时间】:2016-07-21 00:03:09
【问题描述】:
我正在尝试使用mongodb-node.js 驱动程序插入包含在任何给定数组中的多个对象。我的意图是修改每个对象的内容并立即将这些对象保存在数据库中。下面的代码说明了我想要做什么。
var MongoClient = require("mongodb").MongoClient;
var URL = "mongodb://localhost:27017/database";
MongoClient.connect(URL, function(err,db) {
if(err) console.log(err);
var array = []; // an array that serves as a data source
for(var i=0; i<10; i++) {
array.push({ key: i });
};
db.collection("collection_name", function(err,col) {
if(err) console.log(err);
// --- "document insertion" --- //
array.forEach(function(doc) {
col.insert(doc);
});
// --- "document insertion" --- //
});
});
这完全没问题,因为数组中的每个对象都插入到数据库中。但是,我想多次执行此操作;换句话说,我试图在for循环或while循环中运行“文档插入”代码,其中数据在每次迭代中由某个函数修改,然后保存在mongoDB中,但这根本行不通。
我尝试了以下方法,但没有成功,因为好像 for 循环和 while 循环只执行了一次。
// --- "document insertion" --- //
for(var j=0; j<n; j++) { /* where n > 1 */
/* someFunction() might be executed to alter the content of the objects */
array.forEach(function(doc) {
col.insert(doc);
});
};
// --- "document insertion" --- //
这也不起作用。
// --- "document insertion" --- //
while(--n) { /* where n > 1 */
/* someFunction() */
array.forEach(function(doc) {
col.insert(doc);
});
};
// --- "document insertion" --- //
我想对包含更复杂架构设计的大型数组(大于 10k 个文档)执行此操作多次。 for 或 while 循环 试图模拟时间的步伐,并且数组中的每个对象都应该随着时间的推移而变化。我的目标是保存数组中所有对象的每个时间步。鉴于“文档插入”一段代码似乎只执行一次,我怎么能做到这一点?我希望我已经清楚地表达了自己。
任何评论都会受到欢迎和赞赏。感谢您的帮助。
【问题讨论】: