Search code examples
mongodbmeteormeteorite

Access to collection from client folder


Hi im getting started with meteor, so i have a problem: I can't access to collection from client folder my project struct is default: meteor create testApp

/testApp
--.Meteor/
--testApp.html
--testApp.css
--testApp.js

then i create a mongo collection i add it to testApp.js

city = new Mongo.Collection('data');

running the app with meteor command, then i access to chrome console city.find().fetch(); it work perfect and it return the cities

but when i move testApp.js , testApp.css , testApp.html to new folder named /client

/testApp
--.Meteor/
--client/
----testApp.html
----testApp.css
----testApp.js

i cant get the collection from chrome console it mean city.find().fetch(); return []

any idea ?


Solution

  • This is normal behavior. client and server are considered special folders by meteor, where respectively only the client or the server will execute the code that they contain. It is the equivalent of an implicit if (Meteor.isServer)

    When you declare a collection in the client folder only, it will only create an empty collection in your client-side database, MiniMongo. Therefore, your MiniMongo collection has no link to any server-side, "real" mongodb collection. That is why you cannot access the data saved into your actual mongodb database.

    So in order to fix this, what you can do is either:

    • declare your collection once in a separate js file, outside of your client and server folders so that both sides are aware of that collection (recommended in most cases). I use a collections folder at the root of my app for that
    • declare your collection twice : once in your client folder like you did, and another time in the server folder at the root of your app (useful in specific cases such as capped collections, etc)