Google News
logo
Meteor.js - Interview Questions
MongoDB collections in Meteor.
At its core, a web application offers its users a view into, and a way to modify, a persistent set of data. Whether managing a list of todos, or ordering a car to pick you up, you are interacting with a permanent but constantly changing data layer.
 
In Meteor, that data layer is typically stored in MongoDB. A set of related data in MongoDB is referred to as a “collection”. In Meteor you access MongoDB through collections, making them the primary persistence mechanism for your app data.

Server-side collections : When you create a collection on the server:
Todos = new Mongo.Collection('todos');
You are creating a collection within MongoDB, and an interface to that collection to be used on the server. It’s a fairly straightforward layer on top of the underlying Node MongoDB driver, but with a synchronous API:
// This line won't complete until the insert is done
Todos.insert({_id: 'my-todo'});
// So this line will return something
const todo = Todos.findOne({_id: 'my-todo'});
// Look ma, no callbacks!
console.log(todo);
Client-side collections : On the client, when you write the same line:
Todos = new Mongo.Collection('todos');
It does something totally different!
 
On the client, there is no direct connection to the MongoDB database, and in fact a synchronous API to it is not possible (nor probably what you want). Instead, on the client, a collection is a client side cache of the database. This is achieved thanks to the Minimongo library—an in-memory, all JS, implementation of the MongoDB API.
// This line is changing an in-memory Minimongo data structure
Todos.insert({_id: 'my-todo'});
// And this line is querying it
const todo = Todos.findOne({_id: 'my-todo'});
// So this happens right away!
console.log(todo);
The way that you move data from the server (and MongoDB-backed) collection into the client (in-memory) collection is the subject of the data loading article. Generally speaking, you subscribe to a publication, which pushes data from the server to the client. Usually, you can assume that the client contains an up-to-date copy of some subset of the full MongoDB collection.
 
To write data back to the server, you use a Method, the subject of the methods article.
 
Local collections : There is a third way to use a collection in Meteor. On the client or server, if you create a collection in one of these two ways:
SelectedTodos = new Mongo.Collection(null);
SelectedTodos = new Mongo.Collection('selectedtodos', {connection: null});
This creates a local collection. This is a Minimongo collection that has no database connection (ordinarily a collection would either be directly connected to the database on the server, or via a subscription on the client).
 
A local collection is a convenient way to use the full power of the Minimongo library for in-memory storage.
Advertisement