Not able to get objectId in query.containedIn query with parse? - javascript

I am using parse.com as my back end.
I am using containedIn query to retrieve multiple user rows from parse "User" table.
My problem is that I am not able to get user's object Id in the success block
following is my code:
r_userIdList= ['PzpdRdKTVZ','PoJdRdKTVU','fvdRdKTVX'];
var query = new Parse.Query("_User");
query.containedIn("objectId", r_userIdList); // returns multiple rows
query.find({
success: function(r_uobject) {
var userObjId ,fName,lName,full_Name="Unknown User";
for(var i =0; i<r_uobject.length;i++){
var r_obj = r_uobject[i];
uID = r_obj.get('objectId');//not working
var u = uID.id;//not working
fName = r_obj.get('firstName');
lName = r_obj.get('lastName');
full_Name = firstName+' '+lastName;
r_userIdList[u].fullName = full_Name; //not working
}
}
});
Once I enter in the success block, I am unable to identify that which user's data has been retrieved.
Actually I need user's ObjectId because I have array called r_userIdList in which I need to store the firstName and LastName of user as Object.

IDs can usually be accessed with .id - in your case r_obj.id. Your uID.id won't work as uID is itself going to be undefined.
You also need to check that you are getting any results back at all: does r_userIdList have a length?

Related

Getting JSON data from snowflake stored procedure parameter and inserting it in target table

I have a requirement to receive JSON data in a Stored Proc parameter and insert the same in the snowflake target table (user_json_feedback). JSON Data has three key elements(User, EntityID, and Entity Type), whereas the target table has five columns (User, ID, Entity Type, Region, and Date). The region will have a default value of "NA," and the date will be the current date.
If the inserts are successful, it returns true; otherwise, it returns false.
I am struggling with the syntax and parsing issues here, as I am very new to writing procedures.
Here is what I have been trying to do, which is giving me errors obviously but serves the algorithm of my intent.
CREATE OR REPLACE SP_UPDATE_JSON_DATA (JSON_DATA VARIANT)
RETURNS BOOLEAN
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS
$$
//Declare variables
var REGION = 'NA'
var V_DATE = `select current_date;`;
var DATE_STMT= snowflake.createStatement({sqlText: V_DATE });
var curr_date = DATE_STMT.execute();
var src_json = JSON.parse(JSON_DATA);
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region ,date)//
select src_json:USER,src_json:ENTITY_ID,src_json:ENTITY_TYPE,REGION,curr_date;`;
try {
snowflake.execute (
{sqlText: sql_command}
);
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
The function call with parameters will be like
call SP_UPDATE_JSON_DATA ('[{"USER":"XYZ","ENTITY_ID":"BMT0001","ENTITY_TYPE":"BMT"},{"USER":"ABC","ENTITY_ID":"BMT0002","ENTITY_TYPE":"BMT"}]');
Thanks in advance for the help!
theres a few things here.
Firstly the step to get current date. curr_date is a result set object. to extract the value and use it later, you need to read the first row with .next() then GetColumnValue to read the column content. to pass it later as a well formatted string you'll wanna convert with .toISOString().
Secondly the parsed json returns an array in this case so you'll need to iterate over the array to insert the individual records. As it's not known ahead of time if the variant will contain an array you're best checking if the parsed json is an array and handle it accordingly
Last tweak was altering the return type so you get the verbose feedback you're expecting from your return calls.
Updated code:
CREATE OR REPLACE TEMPORARY TABLE user_json_feedback
(
user VARCHAR(100)
,id VARCHAR(100)
,etype VARCHAR(100)
,region VARCHAR(100)
,date TIMESTAMP_NTZ
);
CREATE OR REPLACE TEMPORARY PROCEDURE SP_UPDATE_JSON_DATA(JSON_DATA VARIANT)
RETURNS STRING
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS
$$
//Declare variables
var REGION = 'NA'
var V_DATE = `select current_date;`;
var DATE_STMT= snowflake.createStatement({sqlText: V_DATE });
var DATE_STMT_RES = DATE_STMT.execute();
DATE_STMT_RES.next()
var curr_date = DATE_STMT_RES.getColumnValue(1).toISOString();
var src_json = JSON.parse(JSON_DATA);
try {
if (Array.isArray(src_json)){
for (key in src_json){
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region,date)//
VALUES(:1,:2,:3,:4,:5)`;
snowflake.execute (
{
sqlText: sql_command,
binds: [src_json[key].USER,src_json[key].ENTITY_ID,src_json[key].ENTITY_TYPE,REGION,curr_date]
}
);
}
}
else {
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region,date)//
VALUES(:1,:2,:3,:4,:5)`;
snowflake.execute (
{
sqlText: sql_command,
binds: [src_json.USER,src_json.ENTITY_ID,src_json.ENTITY_TYPE,REGION,curr_date]
}
);
}
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
--Need to cast variable string as variant.
--ARRAY example
call SP_UPDATE_JSON_DATA ('[{"USER":"XYZ","ENTITY_ID":"BMT0001","ENTITY_TYPE":"BMT"},{"USER":"ABC","ENTITY_ID":"BMT0002","ENTITY_TYPE":"BMT"}]'::VARIANT);
--Single object example
call SP_UPDATE_JSON_DATA ('{"USER":"JST","ENTITY_ID":"BMT0003","ENTITY_TYPE":"BMT"}'::VARIANT);
SELECT *
FROM user_json_feedback;
Result set:
While all this works, you may well be better served just inserting the whole variant into a table and relying on snowflake's significant semi-structured data querying capabilities. Certainly for large payloads you'll find much better performance from bulk loading to a variant column in a table then parsing in a view.

Firebase retrieve data under certain child

I was having some trouble when trying to retrieve from firebase. Here is my firebase structure:
What I tried to do is firstly, I wanted to get list of receiptItemID in the first picture. Then, after I get the IDs, for each ID, I wanted to get its quantity and type. After that, I will store them into array and perform some sorting.
Here is my code:
var query = firebase.database().ref('');
query.once( 'value', data => {
data.forEach(subtypeSnapshot => {
var itemKey = subtypeSnapshot.key;
var query = firebase.database().ref('').child(itemKey);
});
});
});
I managed to get the itemKey. However, when I tried to get the details of each receiptItem by the console.log that part, it prints out undefined for both. Any ideas on how to retrieve the data?
You don't need the forEach cycle, it's one level too deep. Instead, use the 'data' argument directly. This new callback should work:
var itemDetail = data.val();
var subtype = itemDetail.type;
var quantity = itemDetail.quantity;
console.log(subtype + ' ' + quantity);
In the first iteration of the forEach of your sample code, itemDetail will be equal to "Farmland" instead of the whole object; thus, subtype and quantity are null. In the new callback, itemDetail will be equal to the whole object, so subtype and quantity can be successfully declared.
var query = firebase.database().ref('receiptItems').child(itemKey);
query.once( 'value', data => {
var itemDetail = data.val();
var subtype = data.type;
// you may try data.toJSON().type as well
var quantity = data.quantity;
// try data.toJSON().quantity
console.log(subtype + ' ' + quantity);
});
In second retrieval you already have access to receiptItems/itemKey .This is a particular entry in receiptItems , not the whole receiptItems array.
So no need to apply data.forEach() once more as there is only one record. We apply data.forEach() to fetch an array of records/object. In your case it is just one entry.

How to get sqlite database Values in javascript

i need how to get values from sqlite Database for particular columns records in Javascript, i successfully inserted values in DB but do no how to fetch the values from db
Here my sample code how i inserted :
var newPath1 = __dirname + path.sep+'schedule.sqlite'
var bfr = fs.readFileSync(newPath1)
var db = new sql.Database(bfr)
db.run("INSERT into
profile_id(SNo,visit_id,date,time,profile_url,First_Name,Last_Name) VALUES
(?,?,?,?,?,?,?)",
[result,result1,date1,time1,sampleUrl,first_Name,last_Name])
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync(newPath1, buffer);
i need a solution from this DB i need to fetch all values from First_Name
Try like this,
var stmt = db.prepare("INSERT into
profile_id(SNo,visit_id,date,time,profile_url,First_Name,Last_Name) VALUES
(?,?,?,?,?,?,?)");
stmt.run(result,result1,date1,time1,sampleUrl,first_Name,last_Name);
stmt.finalize();
db.each("SELECT First_Name FROM profile_id", function(err, row) {
console.log("First Name : "+row.First_Name);
});
finally i found the solution
var fName = db.exec("SELECT First_Name FROM profile_id")
this code works

angularjs Firebase Databse filtering using equalTo and passing an array

I am trying to filter my output of DatabaseONE by values of a child of another DatabaseTWO:
var myquery = DatabaseRef.ref("mydatabaseONE").orderByKey().equalTo("-KUTPrs6ARZXjbjtNr7O");
$scope.mylist = $firebaseArray(myquery);
For my second database, I have set up this service to get the keys and values of the child (i.e. books) I am querying in the DatabaseTWO:
app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
var userId = firebase.auth().currentUser.uid;
userbooks: function() {
return(
DatabaseRef.ref('/users/' + userId).once('value')
.then(function onSuccess(snapshot) {
return snapshot.val().books;
})
);
}
and the result is like this when I call it like below and console log it :
var mybooks = MyUser.userbooks();
My question is how can I pass the values of my DatabaseTWO promise value object into the first query using DatabaseONE and put it as an array in equalTo ? As you can see, I have manually inserted one example value, and it works, but I want to put all three of them (marked in red) as an array?
Or if you have any other creative ideas to filter using equalTo?

CRM: Javascript to Set Multiple Email Addresses when Replying to an Email

On CRM 2013 I'm trying to insert multiple participants into the email "to" field when users click on "Reply All". However I need to remove certain email addresses from the To line. So I created an array to loop and get all the email addresses except the one that needs to be removed.
However the problem here is that it only works if there is only one participant left after removing the unwanted participants. If there are two or more participants the script will not populate any participants at all.
Is there a way to populate multiple email participants? Or is there a better approach than what I'm trying to do here?
Here's my code:
var toParty = Xrm.Page.getAttribute("to").getValue();
var partyListArray = new Array();
for (var indxAttendees = 0; indxAttendees < toParty.length; indxAttendees++) {
// using oData to get participant email address
var email = getParticipantEmail(
toParty[indxAttendees].entityType,
toParty[indxAttendees].id
);
if (email != "test#test.com") {
partyListArray[indxAttendees] = new Object();
partyListArray[indxAttendees].id = toParty[indxAttendees].id;
partyListArray[indxAttendees].name = toParty[indxAttendees].name;
partyListArray[indxAttendees].entityType = toParty[indxAttendees].entityType;
}
}
Xrm.Page.getAttribute("to").setValue(null);
Xrm.Page.getAttribute("to").setValue(partyListArray);
Instead of creating a whole new array, you can delete what you want from the array itself. Try this:
var emails = [{email: "add1#domain.com"}, {email: "add2#domain.com"}, {email: "address#toBe.Removed"}, {email: "add3#domain.com"}, {email: "add4#domain.com"}];
var removeIndex = emails.map(function(item) { return item.email; }).indexOf("address#toBe.Removed");
removeIndex > -1 && emails.splice(removeIndex, 1);

Categories

Resources