Bulk create in Meteor

帅比萌擦擦* 提交于 2019-12-23 04:13:14

问题


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

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

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


回答1:


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

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

Notes:

  • This is not synchronous or isn't run in a fiber as it uses the raw node driver. You need to use Meteor.bindEnvironment or Meteor.wrapAsync to create synchronous code
  • The documents are inserted unordered and may not be in the original order you added them in.
  • It may take 10 seconds for Meteor to see the documents 'Reactively' through a publish method if your instance is not oplog enabled.



回答2:


Extending @Akshat's answer, this is the syntax that would work on 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)();



回答3:


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


来源:https://stackoverflow.com/questions/31131127/bulk-create-in-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!