1

I am new to Meteorjs and I am trying to retrieve data from an already existing MongoDB. Heres what I have so far:

  1. I set the env variable MONGO_URL to the mongoDB url export MONGO_URL="mongodb://username:password@address:port/dbname"

  2. Created a new meteor project with the following code:

    MyCollection = new Meteor.Collection('mycollection');
    
    if (Meteor.isClient) {
        //Meteor.subscribe("mycollection");
        console.log(MyCollection.findOne());
        Template.hello.greeting = function () {
            return MyCollection.findOne();
        };
    }
    
    if (Meteor.isServer) {
        Meteor.startup(function () {
            // code to run on server at startup
            console.log(MyCollection.findOne());
        }); 
    }
    

I know the server side console.log(MyCollection.findOne()); works as it prints out the correct data on the terminal.

The problem is with the client side. When I view the page on my browser, the data is blank and console.log(MyCollection.findOne()); shows 'undefined'.

I know that autopublish is on and I dont have to manually publish the collection from the server side.

I would like to know how I could make the client read from my external mongoDB directly. Let me know if you have any suggestions!

anubhavashok
  • 532
  • 3
  • 15

1 Answers1

0

Even with autopublish on, there is a lag between the client starting and the data being published. At the time that your first console.log is run, the documents haven't finished syncing so the findOne will return undefined. It turns out this isn't a big deal; as you get more familiar with meteor, you will see that the results of find operations are often used in non time-sensitive ways. An easy way to check if the client has the data is just to wait for the page to load, then start the browser console, and manually type:

console.log(MyCollection.findOne());

As for your other problem, the greeting needs to be something that can be displayed in html - a string for example. It can't be a document. Assuming your document had a message property you could do:

return MyCollection.findOne().message;
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Thanks for the help! I didn't know that it takes a while for the data to get published. This led me on the right track and I discovered that the reason it was taking so long was because the db was too big. I tested it on a smaller db and it seems to work. – anubhavashok Feb 02 '14 at 08:02
  • I'm glad that was helpful. Hopefully you can determine a way to publish a smaller subset of the data and improve performance. – David Weldon Feb 02 '14 at 20:31