Next lesson playing in 5 seconds

  • Overview
  • Transcript

2.4 Collections

In Meteor, we use MongoDB as our database. Of course, in typical Meteor style, Meteor has done all of the tedious set up for us, and all that's left for us to do is to create our actual Mongo collections. We don't have to worry about any of the other little bits and pieces that come with setting up or connecting to a database. And we've already created our lib folder. So, in here, let's create a collections.js file. And in here, we're going to put two collections. Now you might think about a database as being a server-side thing. But this file, of course, runs on both the client and the server, because it's in our general lib folder. So, what's going on here? Well, when our collection creation code is run on the server, this is going to be, actually, accessing MongoDB. However, on the client, what happens is it creates a mini-Mongo instance. Now, mini-Mongo is basically a client-side version of MongoDB. And Meteor uses that to manage our data records on the client. And, of course, Meteor will connect that to actual Mongo on the back end, but it gives us a lot of the Mongo methods on the front end. So let's go ahead and create two collections. The first one, of course, is games. So we'll say, Games = new Mongo.Collection. And we'll call it games. Now, you might notice that I did not use the var keyword when creating this game's variable. Even though this is generally a bad practice in JavaScript, this is actually a pattern within Meteor. Whenever we want a function or variable in one file to be accessible in another, we just make it a global variable by not including the var keyword. So we'll just say, Games = new Mongo.Collection, called games. There's one other collection that we're going to need. And this is a conversation's collection. As you saw in the demo, each one of our games will have a conversation to go along with it, new Mongo.Collection, and we'll call it conversations. Now, I will mention right here that in other scenarios, I probably would choose to put the conversation data right inside the game record, so we have the game record with all the game data plus a conversation field, which is an array of the texts back and fourth. The reason we're splitting them into two collections here is just to create a bit more complexity in our application. So you can see what building an application that has more than one collection would be like. To be honest, it doesn't add a whole lot of complexity to the application, but it will give you a taste of using multiple collections. So, in the last lesson, we created user accounts and by default, Meteor will give us a user's collection to work with. So with our user collection, and now our games and conversations collections, we now have all the data structures we will need to build our application.

Back to the top