Rishav Sharan
Rishav Sharan

Reputation: 2932

inserting json data in meteor collection

Here's my code. https://github.com/StudioMockingbird/SH_meteor

its just the leaderboard example wwhere i am trying to insert some of my own data in the collections.

my data resides in lib/book.js and has been defined as an object (var myBook).

the code that I use for inserting is in leaderboard.js as -

Pages = new Meteor.Collection("pages");
if (Meteor.isServer) {
    Meteor.startup(function () {
        if(Pages.find().count() === 0){
            var pages = JSON.parse(myBook.stories);
            for (page in pages) {
                Pages.insert(pages[page]);
            }
        }
    });
}

when i try to run my code it gives me

Running on: http://localhost:3000/
Exited with code: 1
Exited with code: 1
Exited with code: 1
Your application is crashing. Waiting for file change.

what am I doing wrong? I am totally new to meteor.

Upvotes: 2

Views: 3142

Answers (2)

ipstas
ipstas

Reputation: 11

Or another way with 'forEach`. I would prefer it because it is 'async'

pages.forEach(function (item, index, array) {
    console.log('inserting book ', item);
    Pages.insert(
        item
    );
});

Upvotes: 0

Tarang
Tarang

Reputation: 75945

There are a couple of things you need to iron out:

Remove the scoping of your book

You've used var myBook, by using var the myBook variable is being scoped, or at least it is with my 0.6.0 rc8, if you're getting the book with console.log don't worry about this now, but if you run into it later if 0.6.0 gives you problems just change it around

Using JSON.parse

You don't need to parse your JSON data into an object as its already declared as one so change:

 var pages = JSON.parse(myBook.stories);

to

var pages = myBook.stories;

With those changes I've managed to get it to function correctly.

Upvotes: 1

Related Questions