Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get values 0 from firebase realtime database as variable in JavaScript. have easy way to get it? (I tried to find from this website but there is only have android).
First you must get a reference to where the data is stored.
let ref = firebase.database().ref("database/path/to/limitedorder/Apoint");
Next, you must choose how you would like to be notified of data changes. For your use case, this would be subscribing to the 'value' event only once. This will return a Promise that resolves with the desired data.
let valuePromise = ref.once('value');
You then need to chain to the promise to handle/manipulate the data returned by the server and/or handle any errors.
valuePromise.then((dataSnapshot) => {
let desiredValue = dataSnapshot.val();
console.log("Desired value: ", desiredValue);
})
.catch((error) => {
console.log("An error occurred:", error);
})
Bringing this altogether gives:
firebase.database().ref("database/path/to/limitedorder/Apoint").once('value')
.then((dataSnapshot) => {
let desiredValue = dataSnapshot.val();
console.log("Desired value: ", desiredValue);
})
.catch((error) => {
console.log("An error occurred:", error);
})
Detailed explanation of these steps is provided in the Firebase RTDB for Web documentation.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
I'm sending data to the target device using device.sendReport(reportID, dataBuffer) of WebHID, but trying to read the response before it gets ready (i.e) the response takes time to be generated.
For now by setting timeout for 10ms, I'm able to get the response. Would like to know if there are any better solution for this.
You haven't said how the device provides the response but I assume that it is in the form of an input report. In that case the Promise returned by sendReport() isn't particularly interesting but instead you want to listen for an inputreport event that will be fired at the HIDDevice. If you want you can turn this into a Promise like this,
const response = new Promise((resolve) => {
device.addEventListener('inputreport', resolve, { once: true });
});
await device.sendReport(...your data...);
const { reportId, data } = await response;
Once the response is received it will be stored in data.
Note that this assumes that the device only generates input reports in response to a request. For a device with more complex communications you may want to have an inputreport event listener registered at all times and process input reports based on their report ID or other factors. HID does not support any backpressure so if you don't have an inputreport event listener registered when a report is sent by the device it will be discarded.
For this type of action you should use asynchronous code. When sending/receiving things to or from a server, this action is a 'Promise' which is asynchronous.
It'll look something like this (using the fetch api as an example):
With callbacks (which are optional)
myFunction = () => {
fetch('POST', data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.warn(error);
});
}
With async/await. This is not recommended in most cases, as this assumes that the request will succeed.
myFunction = async () => {
const response = await fetch('POST', data);
console.log(response);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm new to Firebase and I'm blocked on something. Actually, I've some difficulties reading data from a Firestore Database. My code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.scheduledFunction = functions.pubsub.schedule("* * * * *").onRun(async () => {
console.log("start");
const querySnapshot = await db.collection("Next_callenges").get();
console.log("Let's see :", querySnapshot);
return null;
});
There is no output except this : "let's see : QuerySnapshot{".
To add some context, the objective behind this code is to get the first data inserted in the first database, add it to a second database and delete it from the first one.
As others have commented, the output you get is exactly what is expected from your code: since you log querySnapshot, you get whatever debug output the QuerySnapshot class defines.
If you want to see the data of each document in that query snapshot, you can do:
querySnapshot.forEach((doc) => {
console.log("Document "+doc.id+":", doc.data());
})
Note that this is just using the Firestore API and has nothing to do with the fact that you use Firestore in Cloud Functions. Since Cloud Functions adds quite some complexity to the case, I'd recommend first learning more about the Firestore API in JavaScript by reading its documentation and following its codelab.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Would I be charged for a read when I get the parent document ID of the sub-collection ?
export const GetAllMySubCollectionWithFieldHello = async () => {
const query = await firebase.firestore().collectionGroup("MySubCollection").where("MyField", "==", "Hello").get();
query.forEach(doc => {
console.log(doc.id, ' => ', doc.data()); // Cost me one read for each document found
console.log(doc.ref.parent.parent.id); // This line will it cost me one read again ?
});
};
My understanding is that your .get will incur one read per document. I don't believe that the doc.data() method incurs any cost.
doc.ref.parent.parent.id shouldn't incur any cost. You are not reading anything from Firestore. You can run this command even when offline.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
this is my firebase database
- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)
I want to list all the conversations and its users
this.db.collection('conversations').get().then(querySnapshot => {
querySnapshot.docs.forEach(doc => {
console.log(doc.collection('users').get())
});
});
I´m getting doc.collection is not a function
update: this is what I have after getting the id and making a new query. now the question is. is this performant?
this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
conversationsQuerySnapshot.docs.forEach(doc => {
this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
usersQuerySnapshot.docs.forEach(doc => {
console.table(doc.data());
});
});
});
});
You're looking for doc.ref.collection('users'), since you need go get from the DocumentSnapshot to its DocumentReference through doc.ref.
Note that I find it easiest to spot such mistakes by simply following the types. Your querySnapshot is a QuerySnapshot, which means that your doc is a QueryDocumentSnapshot. Since QueryDocumentSnapshot doesn't have a collection method, it's easier to figure out what's going wrong.
you would call it: db.collection('conversations').doc({docID}).collection('users')
Your current query is set up to look through every conversation and then get every user in each of those. Plus the second part (getting the users) has no base document to pull from, which is why you're seeing an error.
I recommend watching this video
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So I'm having some trouble. I have a map populated from a json file which works perfectly. However the client wants to truncate the description in the pin popup to 300 charters (rather than actually write text that fits). I thought I could change the description in the promise but it's not working, in fact it's having no effect at all. If anyone has an idea how to do this I'd really appreciate it.
fetch('/assets/map/markers.json')
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response error.');
})
.then(charData => {
let mapData = charData.map(item => item.description.split(0, 300).join(" "));
createMap(mapData);
})
.catch(error => {
console.log('There has been a problem: ', error.message);
});
To take some characters out from a string you can use String.prototype.substring().
So change
item.description.split(0, 300).join(" ")
To
item.description.substring(0, 300)