How to check if Meteor's users account is empty? - meteor

I'm trying to create a default user when my Meteor application starts, so I check if there is any user in the users collection, but it doesn't work.
I try this:
if (Meteor.users.find().count() === 0) {
seedUserId = Accounts.createUser({
email: 'f#oo.com',
password: '123456'
});
}
This count() return 0, but in Mongo I have users:
meteor:PRIMARY> db.users.find().count()
>> 2
I try this too:
Meteor.users.findOne()
but returns undefined...
What I'm doing wrong??

You may be seeing a race condition where the server is not fully loaded when your code is executing -- try to wrap your code in Meteor.startup like;
if (Meteor.isServer) {
Meteor.startup(function () {
if (Meteor.users.find().count() === 0) {
seedUserId = Accounts.createUser({
email: 'f#oo.com',
password: '123456'
});
}
});
}

Related

Add accountStatus to new users on app startup

I'm trying to add accountStatus to the users I create when I first run the application however it keeps crashing. accountStatus is not part of user.profile.
Can someone please look at my code and tell me what I'm doing wrong.
Thanks for any help.
Path: server.js
// run at Meteor app startup
Meteor.startup(function(options, user) {
// if users database is empty, seed these values
if(Meteor.users.find().count() < 1) {
// users array
var users = [
{firstName: 'Sam', lastName: 'Smith', email: 'sam#gmail.com', roles: ['is_student']},
];
// user creation
_.each(users, function(userData) {
// return id for use in roles assignment below
var userId = Accounts.createUser({
email: userData.email,
password: 'password',
profile: {
firstName: userData.firstName,
lastName: userData.lastName,
}
});
// verify user email
Meteor.users.update({ _id: userId }, { $set: { 'emails.0.verified': true } });
// add roles to user
Roles.addUsersToRoles(userId, userData.roles);
// add accountStatus and set to true
_.extend(userId, { accountStatus: true });
});
console.log('New users created!');
}
});
Look at this line:
_.extend(userId, { accountStatus: true });
And look at _.extend definition:
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.
What this line is supposed to do?

How to get user ID during user creation in Meteor?

I am creating default users on the server with a Meteor startup function. I want to create a user and also verify his/her email on startup (I'm assuming you can only do this after creating the account).
Here's what I have:
Meteor.startup(function() {
// Creates default accounts if there no user accounts
if(!Meteor.users.find().count()) {
// Set default account details here
var barry = {
username: 'barrydoyle18',
password: '123456',
email: 'myemail#gmail.com',
profile: {
firstName: 'Barry',
lastName: 'Doyle'
},
roles: ['webmaster', 'admin']
};
// Create default account details here
Accounts.createUser(barry);
Meteor.users.update(<user Id goes here>, {$set: {"emails.0.verified": true}});
}
});
As I said, I assume the user has to be created first before setting the the verified flag as true (if this statement is false please show a solution to making the flag true in the creation of the user).
In order to set the email verified flag to be true I know I can update the user after creation using Meteor.users.update(userId, {$set: {"emails.0.verified": true}});.
My problem is, I don't know how to get the userID of my newly created user, how do I do that?
You should be able to access the user id that is returned from the Accounts.createUser() function:
var userId = Accounts.createUser(barry);
Meteor.users.update(userId, {
$set: { "emails.0.verified": true}
});
Alternatively you can access newly created users via the Accounts.onCreateUser() function:
var barry = {
username: 'barrydoyle18',
password: '123456',
email: 'myemail#gmail.com',
profile: {
firstName: 'Barry',
lastName: 'Doyle'
},
isDefault: true, //Add this field to notify the onCreateUser callback that this is default
roles: ['webmaster', 'admin']
};
Accounts.onCreateUser(function(options, user) {
if (user.isDefault) {
Meteor.users.update(user._id, {
$set: { "emails.0.verified": true}
});
}
});

Meteor - Cannot access custom user field upon registration

Upon a user registration, I've added a new field for a Meteor user using React as my front end:
React component:
Accounts.createUser({
email: trimInput(this.state.email),
password: this.state.password,
username: trimInput(this.state.username),
regId: 1, // I need to access this to show/hide fields elsewhere.
});
Server:
// I assume this is how it's done?
Accounts.onCreateUser(function(options, user) {
user['regId'] = options.regId
return user
});
In meteor mongo I can see the newly added field: "regId": "1". Great. Now in browswer console: Meteor.user.find().fetch() does not include the field. Meteor.user().regId returns undefined. Huh?
What is the correct way to approach something like this?
I think previous answer is good, but you should improve in order to remove
Meteor.subscribe("userData");
in every controller by publish automatically.
`Meteor.publish(null, function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'regId': 1}});
} else {
this.ready();
}
});`
Based on the documentation, I needed to pub/sub the data:
Server:
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'regId': 1}});
} else {
this.ready();
}
});
Client:
Meteor.subscribe("userData");
Now you'll have access to Meteor.user().regId

AngularFire login with google, using parameters

we are using this code to login with google:
var googleOptions = {
scope: 'email'
};
$scope.auth.$authWithOAuthPopup("google", googleOptions).then(function(authData) {
console.log(authData.google.email);
var userSigninIdentifier = authData.google.id;
console.log("userSigninIdentifier:" + userSigninIdentifier);
if ($scope.googleRef.$getRecord(userSigninIdentifier) == null) {
console.warn("new user, registering...");
$scope.register(authProvider, authData);
} else {
$scope.profileID = $scope.googleRef.$getRecord(userSigninIdentifier).profileID;
$firebase(ref.child("users").child("signin").child("google").child(userSigninIdentifier)).$update({
token: authData.token,
expires: authData.expires,
AccessToken: authData.google.accessToken
});
$firebase(ref.child("users").child("data").child($scope.profileID)).$update({
displayName: authData.google.displayName,
email: authData.google.email,
picture: authData.google.cachedUserProfile.picture
});
console.log("Logged in as:", authData.uid);
$state.go('app.home');
}
}).catch(function(error) {
console.error("Authentication failed google:", error);
});
Unfortunately, the options don't work. And since the options don't work, we can't access the users email adress. How do we use AngularFire's $authWithOAuthPopup method with parameters?
Edit: this (in a slightly different form) works perfectly with facebook login

How would I use Accounts.createUser in Meteor once, at first load, and then persist

I have thought of somehow using session, but that doesn't make much sense to me with a user that I always want to exist, and not be created over and over.
My issue is after a page refresh I get an error saying user already exists, I would like to know how to create a permanent user once.
This is in my server code.
Accounts.createUser({
username: "admin",
password: "password"
});
Try this.
Meteor.startup(function () {
if (Meteor.users.find().count() === 0) {
Accounts.createUser({
username: 'admin',
email: 'admin#admin.com',
password: 'password'
});
console.log('created user');
}
});

Resources