[英]Bulk create in Meteor
I need to create 2000 documents at once in Meteor.我需要在 Meteor 中一次创建 2000 个文档。 I know I can use
我知道我可以使用
for (i=0; i<2000; i++) {
CollectionName.insert({});
}
but I hope there is a bulk create function in Meteor.但我希望 Meteor 中有一个批量创建功能。 How can I insert these 2000 rows in the fastest way possible?
如何以最快的方式插入这 2000 行?
Meteor doesn't natively support this. Meteor 本身并不支持这一点。 However, it does give you access to the node Mongodb driver which can natively do a bulk insert.
但是,它确实让您可以访问节点 Mongodb 驱动程序,该驱动程序本身可以进行批量插入。
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)
});
Or with MongoDB 2.6 if your Meteor instance has access to it:或者使用 MongoDB 2.6,如果您的 Meteor 实例可以访问它:
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 } );
Notes:笔记:
Extending @Akshat's answer, this is the syntax that would work on Meteor 1.0+扩展@Akshat 的答案,这是适用于 Meteor 1.0+ 的语法
x = new Mongo.Collection("x");
var bulk = x.rawCollection().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 } );
Meteor.wrapAsync(bulk.execute)();
Here's what I use:这是我使用的:
/server/fixtures.js
var insertIntoCollection = function(collection, dataArray){
dataArray.forEach(function(item){
collection.insert(item);
});
};
if (Stuff.find().count() === 0) {
var array = [
{
// document1
},{
// document2
}
];
insertIntoCollection(Stuff, array);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.