I'm trying to create a new collection 'profile' when Accounts.onCreateUser is run however I'm getting a ReferenceError: Profile is not defined. I assume it's a load order problem. If I move the schema file into a lib folder it works however I'm trying to use the file structure that is now recommended on the Meteor site.
Can some please let me know what I'm missing. I'm new to import and export to so it might be related to that.
Path: imports/profile/profile.js
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
SimpleSchema.debug = true;
Profile = new Mongo.Collection("profile");
Profile.allow({
insert: function(userId, doc) {
return !!userId;
},
update: function(userId, doc) {
return !!userId;
},
remove: function(userId, doc) {
return !!userId;
}
});
var Schemas = {};
Schemas.Profile = new SimpleSchema({
userId: {
type: String,
optional: true
},
firstName: {
type: String,
optional: false,
},
familyName: {
type: String,
optional: false
},
});
Profile.attachSchema(Schemas.Profile);
Path: server/userRegistration/createUser.js
Meteor.startup(function () {
console.log('Running server startup code...');
Accounts.onCreateUser(function (options, user) {
if (options.profile && options.profile.roles) {
Roles.setRolesOnUserObj(user, options.profile.roles);
Profile.insert({
userId: user._id,
firstName: options.profile.firstName,
familyName: options.profile.familyName,
});
}
if (options.profile) {
// include the user profile
user.profile = options.profile;
}
return user;
});
});
In your createUser file you need to import the Profile collection. Any files in the imports directory aren't loaded automatically by Meteor, so you need to import them any time you use them. This is why it is working when the file is in the /lib
directory but not the /imports
directory.
You can import the collection and fix the problem with the following code in your createUser.js
file:
import { Profile } from '/imports/profile/profile';
EDIT
I didn't spot that you weren't exporting the collection definition. You need to export the collection definition so that it can be imported elsewhere. Thanks to Michel Floyd for pointing this out. You do that by modifying your code to the following:
export const Profile = new Mongo.Collection( 'profile' );