Collection repeating on refresh


#1

I have this code for my collection

TeeTimes = new Mongo.Collection(‘times’);
if(TeeTimes.find().count() === 0) {
TeeTimes.insert({Time: “8:00am”});
TeeTimes.insert({Time: “8:30am”});
TeeTimes.insert({Time: “9:00am”});
{

Every time the server refreshes it is still adding times to the database. So where I start with a few on run I end up with 100s after many refreshes. How do i stop that to only add it once?


#2

The problem is that (TeeTimes.find().count()) answer can be different each time you run it.
If you run it and the publication has not finished loading on the client, the insertions will happen.
Run this code on the server and it will work.
On the client, don’t code like that, adopt a reactive programing style.


#3

So if I am understanding correctly. I need to move the if statement and insert to the if server. Then subscribe to the content on the client side? I am very new to this and working on a project for class.


#4

Put your code in a file in a server/ folder, that way it will be only executed by the server.
If you are starting to play with meteor, autopublish is still on, and you don’t even need to subscribe/publish the data, it will be automatically sent to the client. After that, you can learn about publications in the documentation.