How to obtain objectId from a parse user? - javascript

When I print user, I get : {"objectId":"insertSomeValue"} as output. But I cannot obtain the value of that objectId and store it in a string variable. How do I obtain it?
I tried user.get("objectId") and user["objectId"] but they just return "No message provided" when fed to console.log. Do I have to fetch user before I can get its objectId?
var query = new Parse.Query("HelperRating");
var newProfiles = {};
var eachPromise = Parse.Promise.as();
eachPromise = eachPromise.then(function() {
return query.each(
function (helperRating) {
var user = helperRating.get("helper");
var userId = user.objectId; // How do I get this?
console.log(user);
console.log(user.get("objectId")); // I tried these but it prints "No message provided" instead
//console.log(user["objectId"]);
var newRating = helperRating.get("rating");
// Calculate without querying
if (newProfiles.hasOwnProperty(userId)) {
newProfiles[userId][0] = 10;
} else {
newProfiles[userId] = [];
newProfiles[userId].push(1);
}
return;
}
);
return eachPromise;
}).then(function(){
var promises = [];
for (var userId in newProfiles) {
if (newProfiles.hasOwnProperty(userId)) {
var query = new Parse.Query("UserProfile");
query.equalTo("owner", userId);
var promise = query.find().then(
function (results) {
// Do something
}
);
promises.push(promise);
}
}
return Parse.Promise.when(promises);
});

The objectId in the JS SDK is given by var userId = user.id

Related

XSJS getting result from stored procedure in a variable

I have a situation where I pass a session user as a parameter to stored procedure and get a receiver value which I want to get in a variable so I can pass that to other function in xsjs file to send email.
I am getting sender from session user and doing concat to get sender email.
I am calling ReadAuditUser stored procedure will see if the appuser(session user) is valid or not
if ReadAuditUser stored procedure finds appuser as a valid user then stored procedure will return a single record which will return receiver,
if ReadAuditUser stored procedure finds appuser as a invalid user then the stored procedure will return 'null'.
I want to capture that receiver from getReceivername(), like I have capture appuser from getUsername()function.
Please let me know where I am going wrong.
function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);
function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
return xreceiver; /* have to add this code line and it works*/
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);

Firebase Cloud Function error, Function returned undefined, expected Promise or value

I have a cloud function which triggers on certain database write(onCreate), it works as expected but it also throws an error "Function returned undefined, expected Promise or value" though I am returning a promise.
Attaching the code snippet below. there are nested promises in it. is there a better way to handle nested promises, I already checked many posts for nested promises but not able to figure out a proper solution.
Thanks in Advance
exports.calculateAnswer = function(snap, context, dbPath,bucket) {
const answerKey = snap.val();
const incidentId = context.params.incidentId;
const matchId = context.params.match;
var globalIncidentPath = globalIncidentRootPath.replace('${match}', matchId);
globalIncidentPath = globalIncidentPath + incidentId + '/'
var pdPath = pdRootPath.replace('${match}', matchId);
pdPath = pdPath + incidentId
pdPath = pdPath + "/" + bucket
var incidentsPath = incidentsRootPath.replace('${match}', matchId);
var earningsNodePath = earningsNodeRootPath.replace('${match}', matchId);
let app = admin.app();
var globalData = null;
var globalData = null;
const globalPromise = app.database(dbPath).ref(globalIncidentPath).once('value').then(function(snapshot) {
globalData = snapshot.val();
console.log("globalData ",globalIncidentPath, "data ",globalData);
if(globalData) {
console.log("fetching pddata")
return app.database(dbPath).ref(pdPath).once('value')
}
else{
console.log("No global data found");
return true
}
}).then(function(pdSnashot){
const pdData = pdSnashot.val()
if(pdData) {
var promises = []
pdSnashot.forEach(function(childSnap){
console.log('key ',childSnap.key)
console.log('users count ',childSnap.numChildren())
childSnap.forEach(function(usersSnap){
const userId = usersSnap.key
const incidentProcessed = incidentsPath + userId + '/processed/' + incidentId
if (childSnap.key === answerKey) {
const earningUserIdEPath = earningsNodePath + userId
//const earningEPath = earningUserIdEPath + '/e/'
let gocashValue = globalData['v'];
const earningFetchPromise = app.database(dbPath).ref(earningUserIdEPath).once('value').then(function(snapshot1){
let snapDict = snapshot1.val();
var newGoCash = gocashValue
var newPDGoCash = gocashValue
if (snapDict){
let currentGoCash =snapDict['e'];
let currentPDCash = snapDict['pd']
if(currentGoCash) {
newGoCash = currentGoCash + gocashValue;
}
if(currentPDCash) {
newPDGoCash = currentPDCash + gocashValue;
}
}
const obj = Object()
obj["e"] = newGoCash
obj["pd"] = newPDGoCash
const earningPromise = app.database(dbPath).ref(earningUserIdEPath).update(obj)
const tempGlobal = globalData
tempGlobal["skip"] = false;
const processedPromise = app.database(dbPath).ref(incidentProcessed).set(tempGlobal)
return Promise.all([earningPromise,processedPromise])
});
promises.push(earningFetchPromise)
}
else{
const tempGlobal = globalData
tempGlobal["skip"] = true;
const processIncidentPromise = app.database(dbPath).ref(incidentProcessed).set(tempGlobal);
promises.push(processIncidentPromise)
}
})
})
return Promise.all(promises).then(value => {
console.log("Pd promises completed",value);
return true
})
}
else{
console.log("No Pd Data Found");
return true
}
})
.catch(function(error){
console.log('error in promise resolve',error)
})
console.log('global promise',globalPromise)
return Promise.all([globalPromise])
})
I would modify your code as follows. See the comments within the code.
var globalData = null;
const globalPromise = app
.database(dbPath)
.ref(globalIncidentPath)
.once('value')
.then(function(snapshot) {
globalData = snapshot.val();
console.log('globalData ', globalIncidentPath, 'data ', globalData);
if (globalData) {
console.log('fetching pddata');
return app
.database(dbPath)
.ref(pdPath)
.once('value');
} else {
console.log('No global data found');
// return true; Better to throw an error here
throw new Error('No global data found');
}
})
//The following 3 lines don't bring anything
//Moreover they are most probably the reason of your error as you don't return anything in this then()
//.then(function(pdSnashot){
// console.log("");
//})
.catch(function(error) {
console.log('error in promise resolve', error);
return true;
//Note that if you don't need the console.log you may ommit the entire catch since the platform will handle the error itself.
});
console.log('global promise', globalPromise);
//return Promise.all([globalPromise]); // There is no reason to use Promise.all() here since there is only one promise chain returned in globalPromise
return globalPromise;

Node.js to return true or false after querying sqlite3

I am trying to query sqlite3 from node function. Depending on result it should return TRUE or FALSE back to the calling code. This is what I have done, but always get 'undefined':
var sqlite3 = require("sqlite3").verbose();
var dbOpen = function dbOpen() {
sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database('./internaldb/OPMSE.db');
}
module.exports.dbOpen = dbOpen;
dbOpen();
mKey = 'AIzaSyCrIYuHJ_jiZqmGYoAs7mxiloB3-OBx5WI';
async function db1() {
function db2() {
db.each("SELECT STATUS status FROM API_Keys WHERE KEY = ? AND STATUS = ?", [mKey, '1'], (err, row, x) => {
var keyValid = false;
if (err) {
console.log('There is an error in API Validation')
} else {
console.log(keyValid + '<--This is from upper fun')
keyValid = true;
return keyValid;
}
db.close();
return keyValid;
});
} // db2
d = await db2();
console.log(d + '<--Supposed to return TRUE or FALSE')
} //db1
x = db1();
console.log(x)
/*Returns:
Promise { <pending> }
undefined<--Supposed to return TRUE or FALSE
false<--This is from upper fun
*/
If you let db2 return a promise it will work, if you want to know if the key is in the database it would be better to select count it'll return one record and you don't need db.each (not sure what the method is to get one record).
Here is the code with some comments, this should work:
var sqlite3 = require("sqlite3").verbose();
var dbOpen = function dbOpen() {
sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database('./internaldb/OPMSE.db');
}
module.exports.dbOpen = dbOpen;
dbOpen();
mKey = 'AIzaSyCrIYuHJ_jiZqmGYoAs7mxiloB3-OBx5WI';
async function db1() {
function db2() {
//return a promise
return new Promise(
(resolve,reject)=>
db.serialize(
function() {
var keyValid = false;
db.each(//maybe not use each but just get one record and select count(*)
"SELECT STATUS status FROM API_Keys WHERE KEY = ? AND STATUS = ?",
[mKey, '1'], (err, row, x) => {
if (err) {
reject(err);//reject on error
} else {
console.log(keyValid + '<--This is from upper fun');
keyValid = true;
}
}
);
db.colose();
}
)
)
} // db2
d = await db2();
console.log(d + '<--Supposed to return TRUE or FALSE')
} //db1
x = db1();
console.log(x)

Response not return full object after filter [Express.js]

I have in function like this:
var newConvs = [];
var tmp;
convs.filter(function (conv) {
tmp = conv;
conv = conv.conversation;
conv.reciver = tmp.reciver;
conv.conversationId = tmp._id;
newConvs.push(conv);
});
console.log(newConvs);
res.json({
message: newConvs
});
When I console.log(newConvs) it return full object, but in res.json... I don't get this 2: conv.reciver = tmp.reciver;
conv.conversationId = tmp._id;
Anyone know what is reason?

Extract a value that passed the truth test in a Parse Array

Issue
i saved an array of 2 users in parse , i want to extract in the array only the one who pass the truth test , only the one who is not equal to the current value of parse.User. this is what i'm doing
Array.find(function(e){
return e.id != Parse.User.current().id
})
Doing this return me an undefined value
this is how i'm saving the array
function createRooms(){
var chatRooms = new ChatRooms();
var userOne = Parse.User.current()
var userTwo = AchatsDetailsData.value.seller
var chateur = [userOne, userTwo]
chatRooms.set("lastMessages", "undefined");
chatRooms.set("Users", chateur);
chatRooms.save().then(function(results){
console.log("created")
goToChatDetails()
}, function(error){
})
}
this is how i'm loading the data.
function loadrooms(){
var roomsQuery = new Parse.Query("ChatRooms")
roomsQuery.equalTo("Users", Parse.User.current())
roomsQuery.notEqualTo("lastMessages", "undefined")
roomsQuery.descending("updatedAt")
roomsQuery.find().then(function(results){
roomsAll.refreshAll(results,
function(oldItem, newItem){
return oldItem.id == newItem.id;
},
function(oldItem, newItem){
oldItem.time == newItem.get("updatedAt");
},
function(newItem){
return new Rooms(newItem.id, newItem.get("lastMessages"), newItem.get("Users"), newItem.get("updatedAt"), newItem)
}
)
})
}
function Rooms(id, lastmessage, user, time, parsObject){
var self = this;
this.id = id;
this.lastmessage = lastmessage;
this.user = user.find(function(e){
return e.id != Parse.User.current().id
})
this.RigID = this.user.get("RigID");
this.time = time;
this.userName = this.user.get("nom") + " " + this.user.get("prenom")
this.parsObject = parsObject;
this.userpicture = this.user.get("photo");
this.pics = Observable(function(){
if(this.userpicture == null){
return "http://az664292.vo.msecnd.net/files/B2MmOFAy2wjpUo71-model-045.jpg"
}else{
return this.userpicture
}
})
}
so i have 2 users in the array chateur when i click to createRooms function, i want to extract the user who is not equal to the current user for displaying my chat room
This code works perfectly , i just forget to include my Users array into the query
roomsQuery.include("Users")

Categories

Resources