Retriving split data from firebase - javascript

// how I get the data
db.collection('Pins').get().then(snapshot => {
snapshot.forEach(pinInfo => {
pinsToMap(pinInfo)
});
});
// trying to set the data
function pinsToMap(pinInfo){
let pinName;
let pinCoOrdsLat;
let pinCoOrdsLong;
let pinToMapInfo;
pinName = doc.data().name
pinCoOrds = doc.data().coOrds
pinToMapInfo = doc.data().Info
Pins.child(Pins.coOrds).set({
coOrds: {
0:this = pinCoOrdsLat,
1:this = pinCoOrdsLong,
}
});
}
I am storing data in my database based off a map pin, I am now trying to use the stored data to create a pin on the map of the same place, how do I query out the coOrds in to pinCoOrdsLat / pinCoOrdsLong as this way doesn't seem to be working

If I correctly understand you question, the following should do the trick:
db.collection('Pins').get().then(snapshot => {
snapshot.forEach(pinInfo => {
pinsToMap(pinInfo)
});
});
// trying to set the data
function pinsToMap(pinInfo) { // IMPORTANT! => pinInfo is a DocumentSnapshot
const pinName = pinInfo.data().name
const pinCoOrds = pinInfo.data().coOrds
const pinToMapInfo = pinInfo.data().Info
//pinCoOrds is a JavaScript Array with two elements
const pinCoOrdsLat = pinCoOrds[0];
const pinCoOrdsLong = pinCoOrds[1];
//Use pinCoOrdsLat and pinCoOrdsLong the way you want, e.g. calling a leaflet method
}
You'll find here the doc for a DocumentSnapshot

Related

Can't update firebase collection field - Expected type 'ya', but it was: a custom Ia object

I am trying to make barbershop web app where costumer can see list of free appointments and when they reserve free appointment I want to delete that field from firebase.
I have a collection which represents one barber.
This is how it looks in firebase.
As you see radno_vrijeme is object or map in firebase which contains 6 arrays, and in each array there is list of free working hours.
In my function I am able to do everthing except last line where I need to update firebase collection.
const finishReservation = async () => {
try {
const freeTimeRef = collection(db, `${barber}`);
const q = query(freeTimeRef);
const querySnap = await getDoc(q);
querySnap.forEach(async (doc) => {
const radnoVrijeme = doc.data().radno_vrijeme;
// Find the index of the hour you want to delete
const index = radnoVrijeme["Mon"].indexOf(hour);
// Remove the hour from the array
radnoVrijeme["Mon"].splice(index, 1);
// Update the document in the collection
console.log(radnoVrijeme);
const radnoVrijemeMap = new Map(Object.entries(radnoVrijeme));
await freeTimeRef.update({ radno_vrijeme: radnoVrijemeMap });
});
} catch (error) {
console.log(error);
}
};
I tried to pass it as JSON stringified object, but it didn't work. I always get this error :
"FirebaseError: Expected type 'ya', but it was: a custom Ia object"
When you are trying to fetch multiple documents using a collection reference or query, then you must use getDocs():
const finishReservation = async () => {
try {
const freeTimeRef = collection(db, `${barber}`);
const q = query(freeTimeRef);
const querySnap = await getDocs(q);
const updates = [];
querySnap.forEach((d) => {
const radnoVrijeme = d.data().radno_vrijeme;
const index = radnoVrijeme["Mon"].indexOf(hour);
radnoVrijeme["Mon"].splice(index, 1);
const radnoVrijemeMap = new Map(Object.entries(radnoVrijeme));
updates.push(updateDoc(d.ref, { radno_vrijeme: radnoVrijemeMap }))
});
await Promise.all(updates);
console.log("Documents updated")
} catch (error) {
console.log(error);
}
};
getDoc() is used to fetch a single document using a document reference.

JavaScript: How can I insert an Object into an Array of Objects?

I have this script that takes data from a JSON with almost 100 data, then uses this data to bring the weather from an API and after that, inserts this data into an object (using a for for creating my 100 objects), I would like to add the objects that have a temperature > 99 in one array and the ones that have a temperature < 99 into another I have tried this way but doesn't seem to work, sorry if it's a super fool mistake that I can't see, thanks for your help!
This is my script:
async function calcWeather(){
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
for (var i in info) {
const _idOficina = info[i][0].IdOficina
const _nombreOficina = info[i][0].NombreOficinaSN
const _zona = info[i][0].Zona
const _estado = info[i][0].NombreEstado
const lat = info[i][0].latjson
const long = info[i][0].lonjson
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`
fetch(base)
.then((responses) => {
return responses.json()
})
.then((data) => {
// console.log(data)
var myObject = {
Id_Oficina: _idOficina,
Latitud: data.coord.lat,
Longitud: data.coord.lon,
Ciudad: data.name,
Estado: _estado,
Zona: _zona,
Nombre_Oficina: _nombreOficina,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description
};
// validation
if (myObject.Temperatura < 99){
var lstValid = [];
function pushValid(){
lstValid.push(myObject[i]);
}
pushValid();
console.log(pushValid())
}
});
}
};
Your array is local, so for every object you create new lstValid array with no previous data. The solution is to create the array before fetching the data or before the loop:
async function calcWeather(){
var lstValid = []; // HERE
const info = await fetch('../json/data.json')
.then(function(response) {
return response.json()
});
var lstValid = []; // OR HERE (ONLY ONE OF THEM)
for (...) {
...
}
You'll probably be best served by creating the array outside of that call since you're clearing it every run. Then simply add your object. Like Trincot's comment, i'm not sure what exactly you're indexing.
async function calcWeather(){
var lstValid = [];
....
if (myObject.Temperatura < 99){
lstValid[someindex] = myObject;
}
else{
lstNotValid[someOtherIndex] = myObject;
}
}

How to set the map object into Cypress result json file

I'm using cypress runner to execute the spec file and return the result as like below.
Runner.js:
const cypress = require('cypress');
const param = require("./cypress/support/Param");
async function testRunner(fixture) {
return cypress.run({
config: {
},
env: {
testcaseID: `${fixture}`,
},
spec: './cypress/integration/' + `${param.getSpec()}` + ".spec.js",
});
}
Spec file:
let map = new Map();
describe("How to add map values in the cypress result.json",() =>{
const baseUrl = "https://www.google.com/";
const testData = Cypress.env('fixture')
beforeEach("",()=>{
cy.visit(baseUrl);
});
it("Test Case1: Search the keyword", function () {
cy.xpath("//input[#name='q']").type(testData.searchKeyword);
map.set("UserInput",testData.searchKeyword); //It's just sample
cy.xpath("//input[#value='Google Search']").click();
map.set("customMessage","test"); //It's just sample but actual usecase is different
cy.get("//ul/li[2]").should("be.visible");
});
});
using the below lines to get the result in the main runner:
result = await testRunner(dataSet[i]);
if (result.runs[0].stats.failures === 1) {
console.log(result);
}
The above code is working fine and I can able to get the result.json which contains whether the test case is pass/failed. But In addition I just want to add few more runtime values which I stored in the Map and wanna add those in the Cypress.run return result.
Can someone please suggest me the optimized way to handle this? How can I get some runtime values which is available inside the map and that will be returned along with cypress run result.
Thanks in advance.
Updated:
I just created a Map() variable and calling that variable by using the getter and setter but still no luck.
var EnumPojo = {
LISTENER: new Map(),
get listener()
{
return this.LISTENER;
},
set listener(value)
{
return this.listener =value;
};
}
Called the above map into script:
const runtimeValues = require("../../EnumPojo.js");
describe("How to add map values in the cypress result.json",() =>{
const baseUrl = "https://www.google.com/";
const testData = Cypress.env('fixture')
beforeEach("",()=>{
cy.visit(baseUrl);
});
it("Test Case1: Search the keyword", function () {
cy.xpath("//input[#name='q']").type(testData.searchKeyword);
runtimeValues.LISTENER.set("UserInput",testData.searchKeyword); //It's just sample
cy.xpath("//input[#value='Google Search']").click();
runtimeValues.LISTENER.set("customMessage","test"); //It's just sample but actual usecase is different
cy.get("//ul/li[2]").should("be.visible");
});
});
Runner:
const runtimeValues = require("../../EnumPojo.js");
result = await testRunner(dataSet[i]);
if (result.runs[0].stats.failures === 1) {
console.log(result);
console.log(runtimeValues.LISTENER);
}
Output:
Map{0}
In test, save the map under fixtures
it('my-test', function () {
...
cy.fixture('map.json').then(mapData => {
mapData['my-test'] = JSON.stringify(map) // use unique key for this test
cy.writeFile('./fixtures/map.json', JSON.stringify(mapData))
})
})
In runner,
const fs = require('fs')
cypress.run({...})
.then(result => {
const mapData = fs.readFileSync('./cypress/fixtures/map.json') // adjust path to where script is
/*
mapData is {
'my-test': { ...data here },
'other-test': { ...data here },
}
*/
})
BUT Javascript Map may not serialize correctly, best to convert to object before saving.

How to retrieve entities by passing array of IDs as input in Google datastore?

I am trying to implement the following SQL logic in the datastore,
SELECT * from table where id in [1,2,3,4,5]
Implementing this in datastore, I want to retrieve all the corresponding entities with these IDs as an array.
let employees = []
try {
for (let id of idArray) {
const employee = await employeeRepo.getOneById(workspace, id)
employees.push(employee)
}
} catch (e) {
throw e;
}
This is the naive logic of the function, and I am trying to reduce it to a single query.
Are you using the Node.js library referenced here: https://cloud.google.com/datastore/docs/reference/libraries
There is a function get where you can pass in an array of keys and it will return the array of entities.
https://googleapis.dev/nodejs/datastore/latest/Datastore.html#get
It's possible to do by using get as mentioned in the documentation
Here's an example of how to do it based on your code:
const employee1 = this.datastore.key(['Employee', 1]);
const employee2 = this.datastore.key(['Employee', 2]);
const employee3 = this.datastore.key(['Employee', 3]);
const keys = [employee1, employee2, employee3];
try {
const [employees] = await datastore.get(keys);
} catch (e) {
throw e;
}

How to return an array of children from firebase in React-Native

My Firebase data base contains JSON objects, each with the same parameters as seen below. Firebase data
I want to get an array that has each objects country. So if I have 4,000 objects I want to get an array of 4,000 strings all containing a country.
Right now I can get the console to log all the 4,000 objects into an array using the code below.
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
var data1 = [];
var fireBaseResponse = firebase.database().ref();
fireBaseResponse.once('value').then(snapshot => {
snapshot.forEach(item => {
var temp = item.val();
data1.push(temp);
return false;
});
console.log(data1);
});
}
But when I try doing
var fireBaseResponse = firebase.database().ref().child('country');
I get an array of nothing.
Any help would be great.
As mentioned in the comments, you can create a new temp object containing just country before pushing it into your array.
snapshot.forEach(item => {
var temp = { country: item.val().country };
data1.push(temp);
return false;
});

Categories