Phi Nguyễn Văn
Phi Nguyễn Văn

Reputation: 25

Cannot access collection from client side in meteor

I have a Meteor app where I declared a collection in

imports/api/Dictionary.jsx

in that file:

export const dict = new Mongo.Collection('Dictionary');

then export it and try to fetch data in client folder:

import { Meteor } from 'meteor/meteor';
import {dict} from "../imports/api/Dictionary.jsx";

Meteor.startup(() => {

console.log(dict.find().fetch());

});

But nothing showed in the console. I have tried import and fetch in server and side and everything works fine. I also installed autopublish package.

Upvotes: 1

Views: 214

Answers (3)

Orozcorp
Orozcorp

Reputation: 206

What I would do, instead of importing and exporting is the following

In a file that isnt in a client or server folder

this.Dictionary = new Mongo.Collection(“Dictionary”)

In Meteor you can declare global variables

Upvotes: 0

Michel Floyd
Michel Floyd

Reputation: 20226

Even with autopublish the collection won't be immediately available on startup on the client. Depending on the size of the collection it might take awhile. When you use explicit pub-sub normally you can wait until the subscription is ready before trying to access it.

With autopublish you can try:

Meteor.startup(() => {
  Meteor.setTimeout(() => {
    console.log(dict.find().fetch());
    },
    1000);
  );
});

although you might have to use a bigger number than 1000 if your collection is large.

The real answer is:

  1. Create a publication on the server
  2. Subscribe to it on the client
  3. Wait for the subscription to be ready()
  4. Do your thing

Upvotes: 1

ghybs
ghybs

Reputation: 53205

Subscription takes a little bit of time to receive the documents from the server. Try again after a few seconds.

Once you setup your own publication, you can use the ready callback to execute your operation once the subscription has received a full snapshot of the publication.

Upvotes: 0

Related Questions