Insert data in collection at Meteor's startup

1.8k views Asked by At

I would like to insert data at Meteor's startup. (And after from a JSON file)

At startup, I create a new account and I would like to insert data and link it to this account once this one created.

This is the code that creates the new account at startup:

if(!Meteor.users.findOne({emails: { $elemMatch: { address: "[email protected]"}}})){
    var id = Accounts.createUser({ email: "[email protected]", password: "1234", profile: { name: 'Test' } });
    Meteor.users.update({_id: id }, { $set: { admin: false }});
}

And after that, I need to insert data and link it to this account with its ID. (In different collections).

So I tried to do something like that, but obviously It didn't work:

UserData = new Mongo.Collection('user_data');

    if(!Meteor.users.findOne({emails: { $elemMatch: { address: "[email protected]"}}})){
        var id = Accounts.createUser({ email: "[email protected]", password: "1234", profile: { name: 'Test' } });
        Meteor.users.update({_id: id }, { $set: { admin: false }});
        UserData.insert({
            createdBy: id,
            firstname: "test",
            /* ... */
        });
    }

EDIT

Sorry for not have been clear.

The real issue is the :

UserData = new Mongo.Collection('user_data'); 

declaration is in another file, so I can't do like above.

As it's not in the same file, I tried to get the userId that got "[email protected]" as the email (the account's email created at startup). And once I got it, I want to use it in "createdBy: ID_HERE".

1

There are 1 answers

5
halbgut On BEST ANSWER

Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later.

Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js.

So if you put your insert code into server/fixtures.js it'll work.