Back4app Parse Server Retrieved ObjectId - javascript

hi i wonder why i cannot retrieve an objectId from this json object even i can printout the stringify on console.
I can retrieve all other column with no problem but not objectId. It happen to all table in my back4app Parse server.
i need the objectId in order to update certain column in my program
below is my code
1)
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
let queryResult = await parseQuery
.find()
.then((results) => {
results.forEach((prod) => {
//if i change below to prod.get("objectId") error undefined appear
console.log("Product ID Available : " + prod.get("username"));
});
})
.catch((error) => {
console.log(error);
});
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
try {
let todos = await parseQuery.find();
if (todos.length > 0) {
//if i change below to todos[0].get("objectId") error undefined appear
console.log("yes Approval : " + todos[0].get("companyname"));
} else {
console.log("No Approval");
}
console.log("- value is : " + JSON.stringify(todos));
console.log("----------------------");
} catch (error) {
Alert.alert("Error!", error.message);
}
below is the json printout
[{"sessionToken":"r:d9166aa9d7143463c46725d095b53946","username":"Azha","createdAt":"2021-09-21T15:27:01.088Z","updatedAt":"2021-10-10T13:01:27.126Z","companyname":"XXX","fullname":"XXX","email":"azha#abc.com.my","emailVerified":true,"accesslevel":"Maintenence","companydivision":"Maintenence","position":"Technician","phonenumber":"999","userteam":"B","useremail":"azha#abc.com.my","ACL":{"*":{"read":true},"IuBGmCtxyu":{"read":true,"write":true}},"objectId":"IuBGmCtxyu"}]

Yes i just found my solution. Using object1 below:
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
try {
let todos = await parseQuery.find();
var object1 = JSON.parse(JSON.stringify(todos));
console.log("2- value is : " + object1[0].objectId);
} catch (error) {
Alert.alert("Error!", error.message);
}

Related

How to save thousand data in Parse Platform NodeJS

I am new to the parse platform and i'm trying to insert 81000 rows of data in to the Parse DB, here the code
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
var kp = new Parse.Object("theClass");
kp.save(datakp)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
})
}
There is no error in console log, and no data is saved in Parse DB, but if I only insert 1000 rows, it will save to the database.
EG:
if (dataresult.length > 0) {
res.data.forEach(function (datakp, index) {
if (index < 1000) {
var kp = new Parse.Object("theClass");
kp.save(datakp)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
})
}
}
Thank You
UPDATE
I fix this case based on answer #davi-macêdo
here a complete code
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
const objs = [];
const theKP = Parse.Object.extend("theClass")
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
var thekp = new theKP()
thekp.set(datakp)
objs.push(thekp);
})
}
Parse.Object.saveAll(objs)
.then((res) => {
console.log('oke updated ' + dataresult.length)
}),
(error) => {
console.log('err : '+ error.message)
}
The most efficient way is using Parse.Object.saveAll function. Something like this:
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
const objs = [];
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
objs.push(new Parse.Object("theClass", datakp));
})
}
Parse.Object.saveAll(objs)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
Anyways, since you have no error and no data currently being saved, you might be kitting some memory limit. So that's something you also need to be aware about.
You're probably hitting rate limits, I can't imagine saving 81,000 records in one shot is normal behaviour for many applications.
I looked through the documentation and couldn't find anything that might mention a save limit, however sending 1000 requests would trigger most rate limit protection

react firebase firestore insert json

I am using react with firebase firestore to insert a complete collection with documents that does not already exist in firebase firestore .
With my code however no collection is inserted and I get no error as if nothing happened.
This is the code that returns my json
createJson.js
const jsonArray = [{name:"Bill" , age : "5"} ,{name:"Jom" , age : "3"} ]
return jsonArray;
insertJson.js
import 'firebase/firestore';
const db = firebase.firestore();
export const insertJson = (jsn)=>{
try{
jsn.forEach(itm=>{
let id = db.collection("doctors").doc().id;
db
.collection("doctors")
.doc(id)
.set(itm)
.then(doc=>{
console.log("Doc inserted with " +doc.id);
})
});
}catch(err){
console.log("Error : " +err);
}
}
App.js
useEffect(()=>{
const j = createJson();
insertJson(j);
},[])
So in other words no collection is created with my script with the docs inside .
I would appreciate your help .
You should use the Firestore add() method and Promise.all() as follows:
export const insertJson = (jsn) => {
try {
const promises = [];
jsn.forEach((itm) => {
promises.push(db.collection('doctors').add(itm));
});
Promise.all(promises).then((results) => {
console.log(results.length + ' doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}
or, with map():
export const insertJson = (jsn) => {
try {
Promise.all(jsn.map((itm) => db.collection('doctors').add(itm))).then(
(results) => {
console.log(jsn.length + ' doctors added');
}
);
} catch (err) {
console.log('Error : ' + err);
}
}
If the number of doctors is less than 500 you could also use a batched write.
export const insertJson = (jsn) => {
try {
const batch = db.batch();
jsn.forEach((itm) => {
const docRef = db.collection('doctors').doc();
batch.set(docRef, itm);
});
batch.commit().then((results) => {
console.log('doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}

VueJS: Properties of array undefined after fetching data with axios

Currently I try to develope something with VueJS where I fetch data using Axios and push it into an array.
This is my data object
data() {
return {
uid: [], // Each element contains a JSON containing the node and an array containg UID and operator name
timer: null,
tasks: [],
nodes: [
'assembler',
'device'
]
}
In created I call functions for fetching data via axios
created: function() {
// Get current uids and tasks, if there are any
this.fetchUID()
this.fetchTasks()
}
And this are my methods
methods: {
fetchUID() {
var obj = {}
this.nodes.forEach(node =>
axios.get('http://localhost:8080/' + node)
.then(res => res.data.length > 0 ? obj[node] = [res.data[0].id, res.data[0].operator.name] : console.log("No data found for " + node +
". It seems there is no instance of " + node))
.catch(err => console.log(err))
)
this.uid.push(obj)
},
fetchTasks() {
// console log for testing
console.log(this.uid[0].assembler)
}
}
console.log(this.uid[0].assembler) returns undefined though I can see in the VueJS developer console that uid[0].assembler is defined and should return something. Why does it behave like it does and how can I fix this?
fetchUID is async so execute fetchTasks after completing execution of fetchUID
created: function() {
// Get current uids and tasks, if there are any
this.fetchUID()
// this.fetchTasks() to be executed later
},
methods: {
fetchUID() {
var obj = {}
this.nodes.forEach(node =>
axios.get('http://localhost:8080/' + node)
.then(res => res.data.length > 0 ? obj[node] = [res.data[0].id, res.data[0].operator.name] : console.log("No data found for " + node +
". It seems there is no instance of " + node))
.catch(err => console.log(err))
)
this.uid.push(obj);
this.fetchTasks(); // Execute here
},
fetchTasks() {
// console log for testing
console.log(this.uid[0].assembler)
}
}
I've finally found the answer, the issue lies in this part of the code
fetchUID() {
var obj = {}
this.nodes.forEach(node =>
axios.get('http://localhost:8080/' + node)
.then(res => res.data.length > 0 ? obj[node] = [res.data[0].id, res.data[0].operator.name] : console.log("No data found for " + node +
". It seems there is no instance of " + node))
.catch(err => console.log(err))
)
this.uid.push(obj)
}
The problem is the forEach() as it doesn't really work with async/await. This should do the trick
async fetchUID() {
for(let node of this.nodes) {
try {
const { data } = await axios.get(`http://localhost:8080/${node}`);
if(data.length > 0)
this.uid[node] = [data[0].id, data[0].operator.name];
else
console.log(`No data found for ${node}. It seems there is no instance of ${node}`)
} catch (error) {
// error handling
}
}
}

TypeError: Cannot read property 'json' of undefined google assistant

I'm working on a Bus Stop google assistant script in node.js
I based it on the weather API example by Google. Given the right API key, the weather function will work and return the weather for a place on a date.
The Bus Stop API will return the correct output in the console.log, but the output does not get passed on to the else if statement where the function is called.
I get 2 errors:
"Unhandled rejection" Which can be alleviated by commenting out the reject code in the callBusApi.
"TypeError: Cannot read property 'json' of undefined
at callBusApi.then.catch (/user_code/index.js:45:9)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)" This is where it breaks. I think because it doesn't get the output from the function.
My script looks as follows:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = 'enter a working key';
exports.weatherWebhook = (req, res, re) => {
if(req.body.queryResult.intent['displayName'] == 'weather'){
// Get the city and date from the request
let city = req.body.queryResult.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.queryResult.parameters['date']) {
date = req.body.queryResult.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
res.json({ 'fulfillmentText': output }); // Return the results of the weather API to Dialogflow
}).catch(() => {
res.json({ 'fulfillmentText': `I don't know the weather but I hope it's good!` });
});
}
else if (req.body.queryResult.intent['displayName'] == 'mytestintent'){
callBusApi().then((output) => {
re.json({ 'fulfillmentText': output }); // Return the results of the bus stop API to Dialogflow
}).catch(() => {
re.json({ 'fulfillmentText': `I do not know when the bus goes.` });
});
}
};
function callBusApi () {
return new Promise((resolve, reject) => {
http.get({host: 'v0.ovapi.nl', path: '/stopareacode/beunav/departures/'}, (re) => {
let boy = '';
re.on('data', (d) => {boy+=d});
re.on('end',() => {
let response = JSON.parse(boy)
var firstKey = Object.keys(response['beunav']['61120250']['Passes'])[0];
var timeKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[19];
var destKey = Object.keys(response['beunav']['61120250']['Passes'][firstKey])[1];
let destination = response['beunav']['61120250']['Passes'][firstKey][destKey];
let datetime = response['beunav']['61120250']['Passes'][firstKey][timeKey];
let fields = datetime.split('T');
let time = fields[1];
let output = `Next bus to ${destination} departs at ${time} .`;
console.log(output)
resolve(output);
});
re.on('error', (error) => {
console.log(`Error talking to the busstop: ${error}`)
reject();
});
});
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
http.get({host: host, path: path}, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => {
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
console.log(output);
resolve(output);
});
res.on('error', (error) => {
console.log(`Error calling the weather API: ${error}`)
reject();
});
});
});
}
It appears that your method has a parameter too much
exports.weatherWebhook = (req, res, re) => {
should be:
exports.weatherWebhook = (req, res) => {
And as well on the variable 're' used in the handling of the 'mytestintent' inside the webhook.
This explains the 'not defined' error when trying to set a json value on it.
Regarding your 2 question: It usually comes when the value of the variable is not defined.
First check wheather you have defined the JSON variable in your .js file.
Or its in some other format.

Undefined results when using imported custom nodejs module

I am trying to search my local db for a user by email, but when I try to reference a function that does that from a different js file, via an import, I get undefined results. I have searched a bit on Stack about this issue I am having, and heard of something referred to as a callback, is this something that I would need to implement? If so could you point me to an example ?
Thanks in advance!
Here is my code that is exported (db.js file) :
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
exports.findEmail = (email) => {
// console.log('hi');
session
.run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
email: email
})
.then((result) => {
let result_string = '';
result.records.forEach((record) => {
console.log(record._fields);
result_string += record._fields + ' ';
});
return result_string;
})
.catch((e) => {
return ('error : ' + JSON.stringify(e));
})
}
Here is my code calling the export : (test.js)
var tester = require('./db.js');
let temp = tester.findEmail("testemail#yahoo.com");
console.log(temp);
The thing is that JS is asynchronous, and you using it as it is synchronous code.
Can you try this one, should work:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
const findEmail = (email, callback) => {
console.log('hi :', email);
session
.run("MATCH (a:Person) WHERE a.email = {email} RETURN a.name AS name, a.email AS email, a.location AS location", {
email: email
})
.then((result) => {
let result_string = '';
result.records.forEach((record) => {
console.log(record._fields);
result_string += record._fields + ' ';
});
return callback(null, result_string);
})
.catch((e) => {
return callback('error : ' + JSON.stringify(e)));
})
}
module.exports = {
findEmail
};
Then in test.js:
var tester = require('./db');
tester.findEmail("testemail#yahoo.com", (err, temp) => {
if (err) return console.error(err);
console.log(temp);
} );
The idea behind this is that all the flow in db file is asynchronous.
So in order to catch result you need to pass the function, callback, which will be triggered when the ansynchronous flow is done.

Categories

Resources