在Meteor中批量创建

问题描述:

我需要在Meteor中一次创建2000个文档。我知道我可以使用

I need to create 2000 documents at once in Meteor. I know I can use

for (i=0; i<2000; i++) {
    CollectionName.insert({});
}

但我希望Meteor中有批量创建功能。如何以最快的方式插入这2000行?

but I hope there is a bulk create function in Meteor. How can I insert these 2000 rows in the fastest way possible?

Meteor本身并不支持这一点。但是,它确实允许您访问Mongodb驱动程序,该驱动程序本身可以进行批量插入。

Meteor doesn't natively support this. However, it does give you access to the node Mongodb driver which can natively do a bulk insert.

您只能在服务器上执行此操作:

You can only do this on the server:

var x = new Mongo.Collection("xxx");

x.rawCollection.insert([doc1, doc2, doc3...], function(err, result) {
    console.log(err, result)
});

如果您的Meteor实例可以访问它,可以使用MongoDB 2.6:

Or with MongoDB 2.6 if your Meteor instance has access to it:

var bulk = x.initializeUnorderedBulkOp();

bulk.insert( { _id: 1, item: "abc123", status: "A", soldQty: 5000 } );
bulk.insert( { _id: 2, item: "abc456", status: "A", soldQty: 150 } );
bulk.insert( { _id: 3, item: "abc789", status: "P", soldQty: 0 } );
bulk.execute( { w: "majority", wtimeout: 5000 } );

注:


  • 这不是同步的,也不是在光纤中运行,因为它使用原始节点驱动程序。您需要使用Meteor.bindEnvironment或Meteor.wrapAsync来创建同步代码

  • 文档是无序插入的,可能不是您添加它们的原始顺序。

  • 如果您的实例未启用oplog,Meteor可能需要10秒才能通过发布方法查看文档Reactively。