Is it possible to add several documents to the meteor via collection.insert ()?

I like to add several documents to the collection in meteor at once.

MongoDB supports this from 2.2:

db.collection.insert([{docNumber: 1},{docNumber: 2}]) 

Is it possible to achieve the same behavior in the Meteor? Sort of:

 myCollection.insert([{docNumber: 1},{docNumber: 2}]) 

Currently, this will be added as one document. Unfortunately, I cannot live with an iterator, because in case of use, more than 100,000 documents are loaded. It slows down with separate inserts.

+4
source share
2 answers

Batch installation of Meteor is not yet possible. Although you can do an iterator to help you insert documents into an array

 var docs = [{docNumber: 1},{docNumber: 2}]; _.each(docs, function(doc) { myCollection.insert(doc); }); 

It may be possible to do this on the server, albeit with minor modifications, to expose the bulk insert method. The problem with this, however, is that this code will not work on the client side.

+7
source

I wrote a simple script for bulk insertion. It works only on the client side, inserting documents into the collection without reactivity. only the last element will cause reactive calculations.

 insertBulk = function(collection, documents){ if(collection) { return _.compact(_.map(documents, function(item){ if(_.isObject(item)) { var _id = collection._makeNewID(); // insert with reactivity only on the last item if(_.last(documents) === item) _id = collection.insert(item); // insert without reactivity else { item._id = _id; collection._collection._docs._map[_id] = item; } return _id; } })); } } 

Here you can find an example script, including the removebulk () function: https://gist.github.com/frozeman/88a3e47679dd74242cab

+6
source

Source: https://habr.com/ru/post/1498714/


All Articles