Are ordinary functions blocking in meteor? Consider the function below. If two users access at around the same time, I get
E11000 duplicate key error collection: srs-3_meteor_com.users index: username_1 dup key
That led me to think that, both users checked Meteor.users.findOne at same time, both returning undefined/null, thus user not existing yet. Then both go through and have a race for Meteor.users.insert, in which case, an error is going to occur, whoever is first. Probably, the fibre only guarantees blocking for db ops.
function insert_or_update_moodle_user(login_request) {
check(login_request.lms_id, String);
check(login_request.lms_role, String);
check(login_request.lms_course_id, String);
let username = `moodle-${login_request.lms_id}`;
let user = Meteor.users.findOne({username: username, 'profile.type': 'moodle'});
console.log(username);
// todo: if someohow moodle-<username> was used already, append an incrementor on it based on number of duplicates.
/*
* If user does not exist, create that user. Otherwise,
* update the user's current course and lms_role.
*/
if (!user) {
Meteor.users.insert({
username: username,
password: Meteor.uuid(), // Generate random password. Not to be used for logging, but Meteor requires this.
// LMS specific data.
profile: {
type: 'moodle',
lms_id: login_request.lms_id,
lms_role: login_request.lms_role,
lms_current_course: login_request.lms_course_id
}
});
console.log(username + ' inserted');
} else {
Meteor.users.update({
username: username,
'profile.type': 'moodle'
}, {
$set: {
'profile.lms_current_course': login_request.lms_course_id,
'profile.lms_role': login_request.lms_role
}
});
}
// Get the created/updated user.
return Meteor.users.findOne({username: username, 'profile.type': 'moodle'});
}