How can we insert multiple documents in Mongo FROM JSON?

Hi,

I wish to start from a JSON document received by meteor.call and populate multiple documents in a client side Mongo DB (non connection with a server client).

The JSON contains an array or ideally an array deeper in the object, and I wish to create one document per row in Mongo.

Thanks
Marc

You can follow this basic recipe:

someArrayOfObjects.forEach(doc => {
  someCollection.insert(doc);
});

Edit: If you’ve got actual JSON, you’ll need to JSON.parse first to get an object.

Edit: You may find it’s more efficient to use the underlying Node driver with insertMany:

await someCollection.rawCollection().insertMany(arrayOfDocs);
3 Likes

To make sure the collection is in minimongo, on the client only, and not connected to the server, instantiate your collection using null instead of a collection name:

someCollection = new Mongo.Collection(null);
1 Like

Good call. I misread the original post.

Thanks for the ints, but for now, I cannot fully test it because even though I am having the right Vue.js+Meteor packages, I have problem declaring and using this DB. Maybe I should open another topic.

For now:
MAIN.JS (‘state’ previously populated)

export default {
   const MMtileSets new Mongo.Collection(null)   //MM for MiniMongo
     state.tilesSets.tileSets.forEach(doc => {
     MMtileSets.insert(doc);
   });
} 

generates: const is a reserved word.

for using it in a .vue component, I suppose I should do this, but not sure about this code (taken from another post):

<script>
import {Meteor} from 'meteor/meteor'
export default {
    data() {
            return {
                MMtileSets: []
            };
        },
        meteor: {
            $subscribe: {
                'MMtileSets': []
            },
            MMtileSets() {
                return MMtileSets.find({}, {
                    sort: {createdAt: -1}
                });
            }
        }
    },

}      
</script>

This code does not work neither.