Not able to save a custom class object in Parse - javascript

I am trying to create a Customer class object which has a one to one relation with the User class. But the object doesn't save without giving any error.
Here is my code:
Parse.Cloud.afterSave(Parse.User, function(request) {
user = request.object;
role_name = user.get("role_name");
user_name = user.get("user_name");
user_id = user.get("objectId");
if (role_name == "customer"){
user = request.object;
console.log(" I am inside if else");
var Customer = Parse.Object.extend("Customer");
var cus = new Customer();
cus.set("name2" , "albert")
var relation = cus.relation("userId");
relation.add(user);
cus.save(); // Customer object should get saved here
cus.save(null, {
success: function(cus) {
// Execute any logic that should take place after the object is saved.
console.log("I am working")
alert('New object created with objectId: ' + cus.objectId);
},
error: function(error) {
// handleParseError(error);
console.log(error)
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
}
});
Log when I run this:
after_save triggered for _User for user qu808uKOgt:
Input: {"object":{"createdAt":"2015-10-11T18:36:07.661Z","objectId":"qu808uKOgt","phone":"5678956475","role_name":"customer","updatedAt":"2015-10-11T18:36:07.661Z","username":"newuser16"}}
Result: Success
I am inside if else
{"name2":"apple","userId":{"__op":"AddRelation","objects": [{"__type":"Pointer","className":"_User","objectId":"qu808uKOgt"}]}}

I fixed this bug by creating a new cloud function, which will be called immediately after the user sign's up.
Parse.Cloud.define('functionName', function(request, response){
var currentUser = Parse.User.current();
var role_name = currentUser.get("role_name");
if (role_name == "customer"){
// Do something
}
else if (role_name == "service_provider"){
// Do something else
}
)};

Related

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined when adding object to field in Sharepoint

I want to fill a nintex form people picker field automatically using JavaScript on a SharePoint page.
The problem is that I keep getting an error:
When I click on the first link, it shows this
In the formMain.js, the error is caused by this line:
ins.add(object);
I've been trying for hours to fix this issue, but I can't find a solution.
As you can see in the console, ins and the object are both defined.
Here's the JavaScript I use to add the user to the field:
var personProperties;
function onChangeProductManagement() {
var curvalue = NWF$('#' + TeilnehmerStatus10).find("input:checked").val();
var ins = new NF.PeoplePickerApi('#' + TeilnehmerName10);
if (curvalue == "offen") {
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
// Make sure PeopleManager is available
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', function() {
// Replace the placeholder value with the target user's credentials.
var targetUser = "opmain\\eoblae";
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getPropertiesFor(targetUser);
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
});
});
} else {
console.log("Test2");
console.log("NWF value: " + NWF$('#' + TeilnehmerName10).val());
}
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
var accountName = personProperties.get_accountName();
var displayName = personProperties.get_displayName();
var email = personProperties.get_email();
var object = { value: accountName, label: displayName, type: "user", email: email };
console.log("object: ", object);
var ins = new NF.PeoplePickerApi('#' + TeilnehmerName10);
console.log("ins: ", ins);
ins.add(object);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
console.log("Error: " + args.get_message());
}
Any help is appreciated!
Adding the id in var object fixed the issue.

Incorrect user profile picture being displayed from JS array - How to address this?

Sorry for the long post, but I'm not sure the issue comes across without all the code.
I'm using parse.com and the JavaScript SDK.
The below code is part of my users profile page, it displays their profile picture to them on screen and allows them to change it.
Changing the profile picture works fine and is uploaded as expected. The issue is that on the profile page the profile is taking the first users picture and displaying it on page for any user. Basically its not looking at the current user.
I think that I need to update the query to include something like var currentUser = Parse.User.current(); and introduce it into my code. Whatever why I try and do this I'm hitting a brick wall. Any help would be great
I'm struggling if this is the case to understand how to change my code to avoid this happening?
/////////////////////////Queries the users profile picture and shows on page////////////////////////
var UserProfilePic = Parse.Object.extend("_User");
var query = new Parse.Query(UserProfilePic);
query.exists("ProfilePic");
query.find({
success: function(results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('ProfilePic').url());
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
if (imageURLs.length > 0) {
$('#profile_pic').attr('src', imageURLs[0]);
}
$('#Image01').attr('src', imageURLs[0]); //first image
},
error: function(error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
///////// Saves the users profile image and fields after the #save button is clicked//////
var profileSave = Parse.User.current();
function ProfileSave() {
var User = Parse.Object.extend("_User");
var profileSave = Parse.User.current();
var saveusername = $('#username').val();
var saveemail = $('#email').val();
var savegender = $('#gender').val();
profileSave.set("username", saveusername);
profileSave.set("email", saveemail);
profileSave.set("gender", savegender);
profileSave.save(null, {
success: function(profileSave) {
profileSave.save();
console.log("DONE");
alert("Profile Saved");
},
error: function(profileSave, error) {
// Fail
}
});
}
///////////////Allows the user to upload a profile image and store///////////////////////
$(document).ready(function() {
var parseAPPID = "XXXXXX";
var parseJSID = "XXXXXX";
//Initialize Parse
Parse.initialize(parseAPPID, parseJSID);
$("#fileUploadBtn").on("click", function(e) {
var fileUploadControl = $("#fileUploader")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = file.name;
console.log("here goes nothing...");
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
console.log("Worked!");
console.dir(arguments);
var User = Parse.Object.extend("_User");
var jobApplication = Parse.User.current();
jobApplication.set("ProfilePic", parseFile);
jobApplication.save();
var profilePhoto = jobApplication.get("ProfilePic");
console.log("Done");
//jobApplication.get("ProfilePic").url;
}, function(error) {
console.log("Error");
console.dir(error);
});
}
});
});
Just found this in the featured/bounties, even though I answered it here for you, so here's my copy/pasted answer:
You're not using query.exists() the way you think you are. Also, are you just trying to check to see if the current user has a profile image? Because you can just use the .has("key") method of objects, and a user is an object. If this is in cloud code, rather than client code, you may have to fetch the user first. If it is client code, you should already have an up to date user.
You should not be extending the user object. Not necessary at all. Use the Parse.User object type, so if you're querying for users, do var query = new Parse.Query( Parse.User );
So I think what you want is something more like:
var user = Parse.User.current();
if( user.has("ProfilePic") )
{
//Do your stuff with the image
var imageURL = user.get("ProfilePic").url();
$('#Image01').attr('src', imageURL);
}
else
{
alert("Error: User does not have a 'ProfilePic' set");
}
The way your code is set up, you're just querying through all the users with profilePics and taking the first one. My code only gets the profilePic of the current user.

Exception in async function: Only on server, not on localhost

I am trying to get a route working that will function as a "Thank You" page for people who buy our products on an external store. On localhost everything works fine but on our staging server I get the following exception:
Exception in callback of async function: action#http://taskwunderstaging-45398.onmodulus.net/12289f8cf999b67e6c6c6dcad1a5a5eded53f4e2.js:517:468
Does anyone have an idea what might be causing this?
The code in question is as follows:
The Iron Router Endpoint
Router.route('/signup-partner', {
name: 'signupPartner',
where: 'client',
waitOn: function(){
return Meteor.subscribe("packages");
},
action: function() {
Meteor.logout(function() {});
var query = this.params.query;
//#TODO verify the query with the sha key!
var userInfo = {
email:query.email,
firstname:query.firstname,
lastname:query.lastname,
};
var companyInfo = {
companyName:query.company,
street:query.street,
city:query.city,
zipcode:query.zipcode,
country:query.country,
taxId:query.taxid
};
var orderInfo = {
product:query.product,
order:query.order,
};
// get the package from the database
orderInfo.package = Packages.findOne({digistoreId:orderInfo.product}).name;
orderInfo.tw_id = Packages.findOne({digistoreId:orderInfo.product})._id;
var data = {
userInfo:userInfo,
companyInfo:companyInfo,
orderInfo:orderInfo,
};
var that = this;
// check if the user account already exists and if so add the package and login the user
Meteor.call("partnerUserExists", data.userInfo.email,{orderId:data.orderInfo.order,tw_id:data.orderInfo.tw_id}, function(error, result){
if(result === "not-found"){
that.render('signup_partner',{
data: function(){
return data;
}
});
}
else {
Session.set('boughtPackage',result);
that.redirect('login');
}
});
}
});
the method that this route calls is as follows:
partnerUserExists: function(email,orderIds){
var user = Meteor.users.findOne({"emails.address":email}) || false;
console.log(user);
if(!user){
return "not-found";
}
if(_.indexOf(user.data.digistoreOrders,orderIds.orderId) > -1){
return orderIds.tw_id;
}
(function(callback){
// add the paidTask array if it doesnt exist
if (!user.data.paidTasks){
Meteor.users.update({_id:user._id},{$set:{"data.paidTasks":[]}});
}
// add the digistore array if it doesnt exist
if (!user.data.digistoreOrders){
Meteor.users.update({_id:user._id},{$set:{"data.digistoreOrders":[]}});
}
callback();
})(function(){
Meteor.users.update({_id:user._id},{$push:{"data.digistoreOrders":orderIds.orderId}});
Meteor.users.update({_id:user._id},{$push:{"data.paidTasks":orderIds.tw_id}});
return orderIds.tw_id;
});
}
check for error in your meteor.call. It should tell you if there is an error and why. If not, then try putting a console.log before each return. Overall, I see a lot of user.xx fields being accessed without checking whether that field is set. It could be one of those.

IndexedDB Reference Error: db is not defined

I'm trying to create an application for Firefox OS which basically needs to store some data using IndexedDB.
The store() function is called when the user clicks on a submit button which results in the creation of the name and description variables an user submitted form.
However, I keep getting a Reference Error saying my db object is not defined. Any ideas why this is happening?
Here's my current code:-
function store () {
// create the transaction with 1st parameter is the list of stores and the second specifies
// a flag for the readwrite option
var transaction = db.transaction([ 'Apps' ], 'readwrite');
//Create the Object to be saved i.e. our App details
var value = {};
value.name = name;
value.desc = description;
// add the details to the store
var store = transaction.objectStore('Apps');
var request = store.add(value);
request.onsuccess = function (e) {
alert("Your App data has been saved");
};
request.onerror = function (e) {
alert("Error in saving the App data. Reason : " + e.value);
}
}
$(document).ready(function(){
// variable which will hold the database connection
var db;
if (window.indexedDB) {
console.log("IndexedDB is supported");
}
else {
alert("Indexed DB is not supported!");
}
// open the database
// 1st parameter : Database name. We are using the name 'Appsdb'
// 2nd parameter is the version of the database.
var request = indexedDB.open('Appsdb', 1);
request.onsuccess = function (e) {
// e.target.result has the connection to the database
db = e.target.result;
console.log(db);
console.log("DB Opened!");
}
request.onerror = function (e) {
console.log(e);
};
// this will fire when the version of the database changes
// We can only create Object stores in a versionchange transaction.
request.onupgradeneeded = function (e) {
// e.target.result holds the connection to database
db = e.target.result;
if (db.objectStoreNames.contains("Apps")) {
db.deleteObjectStore("Apps");
}
// create a store named 'Apps'
// 1st parameter is the store name
// 2nd parameter is the key field that we can specify here. Here we have opted for autoIncrement but it could be your
// own provided value also.
var objectStore = db.createObjectStore('Apps', { keyPath: 'id', autoIncrement: true });
console.log("Object Store has been created");
};
});
The problem is with the scope of the db variable. Currently you have the following line var db; declared inside of the $(document).ready function. Move its declaration to a more global scope i.e. outside of this function and the variable will be visible in the store() function too.
Hope this helps.
var value = {};
value.name = name;
value.desc = description;
assign value to the name and description.
name=formname.name.value
description=formname.description.value

Node Fibers Trouble with Meteor

I'm trying to write a simple authentication backend for Meteor that authenticates against an LDAP server. I need the function registered as login handler (the input to Accounts.registerLoginHandler) to return the id the of the user just logged in.
The problem I think lies in the Fiber I've created, getUserId, and that it's not returning id like I want it to. I know it has to be in a Fiber or else meteor gets angry and throws errors. Even though the log right before the yield shows me the id isn't undefined, getUserId.run() always returns undefined.
Any help would be greatly appreciated, thanks!
Accounts.registerLoginHandler(function(loginRequest) {
console.log("In login handler");
return auth.authenticate(loginRequest.username, loginRequest.password, function(err, ldap_user) {
if (err){
// ldap authentications was failed
console.log("Login failed");
return undefined;
}
else {
// authentication was successful
console.log("Login success");
// extracting team name from ldap record
var equals = ldap_user.memberOf.indexOf("=");
var comma = ldap_user.memberOf.indexOf(",");
var team_name = ldap_user.memberOf.slice(equals+1,comma);
// add user if they don't already exist
var getUserId = Fiber( function() { // Meteor code must be ran within a fiber
var id = null;
var user = Meteor.users.findOne({username: loginRequest.username});
if(!user) {
// insert user and kick back id
id = Meteor.users.insert({username: loginRequest.username,
profile : {team : team_name}
});
console.log('no user found, creating' + id);
} else {
id = user._id;
console.log('user found, returning id' + id);
}
console.log('id: '+id);
Fiber.yield(id); // return id
});
// send logged in users if by executing the fiber
return {id: getUserId.run()};
}
});
});
I think the problem is related to instead needing to use Meteor.bindEnvironment to control the scope of the (environment) variables and fibers in use.
A good three-step tutorial on the subject is found here:
https://www.eventedmind.com/feed/nodejs-introducing-fibers
https://www.eventedmind.com/feed/meteor-dynamic-scoping-with-environment-variables
https://www.eventedmind.com/feed/meteor-what-is-meteor-bindenvironment
My take on your code would be something like this (which in a similar problem worked for me):
Accounts.registerLoginHandler(function(loginRequest) {
console.log("In login handler");
var boundAuthenticateFunction = Meteor.bindEnvironment(function(err, ldap_user) {
if (err){
// ldap authentications was failed
console.log("Login failed");
return undefined;
}
else {
// authentication was successful
console.log("Login success");
// extracting team name from ldap record
var equals = ldap_user.memberOf.indexOf("=");
var comma = ldap_user.memberOf.indexOf(",");
var team_name = ldap_user.memberOf.slice(equals+1,comma);
// add user if they don't already exist
var id = null;
var user = Meteor.users.findOne({username: loginRequest.username});
if(!user) {
// insert user and kick back id
id = Meteor.users.insert({username: loginRequest.username,
profile : {team : team_name}
});
console.log('no user found, creating' + id);
} else {
id = user._id;
console.log('user found, returning id' + id);
}
console.log('id: '+id);
return {id: id};
}
}, function(e){throw e;});
return auth.authenticate(loginRequest.username, loginRequest.password, boundAuthenticateFunction);
});
Mind, the code sample above is untested...

Categories