javascriptnode.jsmongodbmeteorminimongo

inserting/caching in minimongo from Meteor.call


Because I need to pull large amounts of data from the client, I use Meteor.Call to fetch the data. When doing so, the data is not inserted in the minimongo Adapter on the client. Any idea how I can do this ? Can we access the minimongo instance on the client and cache the data without sending it back to the server (meaning not with Collection./insert/upsert/update) ?


Solution

  • You can create a local collection on the client, if you omit the name and insert your data from the method call in there.

    This collection is "unmanaged" and not connected to any server collection. You can then insert the data into the collection locally.

    Some mininmal example to reproduce:

    server/main.js

    import { Meteor } from 'meteor/meteor'
    import { Mongo } from 'meteor/mongo'
    import { Random } from 'meteor/random'
    
    const SomeCollection = new Mongo.Collection('someCollection')
    
    Meteor.startup(() => {
      for (let i = 0; i < 5; i++) {
        SomeCollection.insert({
          key: Random.id()
        })
      }
    })
    
    Meteor.methods({
      'docs' () {
        return SomeCollection.find().fetch()
      }
    })
    

    client/main.js

    import { Meteor } from 'meteor/meteor'
    import { Mongo } from 'meteor/mongo'
    
    const LocalCollection = new Mongo.Collection(null)
    
    Meteor.startup(() => {
      Meteor.call('docs', (err, documents) => {
        documents.forEach(doc => LocalCollection.insert(doc))
        setTimeout(() => {
          console.log(LocalCollection.find().fetch())
        }, 2000)
      })
    })
    

    Client console.log output:

    0: {_id: "fKtSM2GEe3HQutqzf", key: "ndgcSoLDhh4tTekKy"}
    1: {_id: "BcZE9TT9ZF5Qak3As", key: "Nw56vSnCAPtRGfw3j"}
    2: {_id: "nWCD3Kk2arLHBJTN5", key: "ZP8mDaaqimZJQzM8c"}
    3: {_id: "2H3haJiiv23dtJF94", key: "kue8BCWWasJJa74zm"}
    4: {_id: "oDiF7ckK4PAXREFYe", key: "fvbv36kkPWb7uAcfN"}
    5: {_id: "w3fz3GHP9W9suX2NG", key: "Cf6RCy2k3QA9KLxMX"}
    

    There is only a short reference about it in the docs: https://docs.meteor.com/api/collections.html

    If you are looking for persistent caching you may check out ground:db