Im saving my data to database, using React, like this:
export const matchesInitialCreate = (user, matches) => {
return (dispatch) => {
firebaseApp.database().ref(`/users/${user}/matches`)
.push(matches)
.then(() => {
dispatch({ type: MATCHES_INITIAL_CREATE });
});
};
};
My matches entity is a simple json with some data, divided into
matches:{ groups: {...}, knockout {...}}}
Everything looks fine, but when I push it to firebase, it is saved with a hash. Like this:
users/user/matches/CRAZY_HASH/matches/groups
But I want that it saves like this:
users/user/matches/groups
What Im doing wrong?
There are different ways to save data to Firebase Realtime Database.
Push: generates a unique key at the specified reference, and writes the given data under this new child
Set: save data to a specified reference, replacing any existing data at that path
Update: updates lower-level child values of a specified reference
The reason why you see a crazy hash is you are using the push method. If you want to set the data directly under users/{user}/matches/groups, you must use either set or update.
// Will override everything
firebaseApp.database().ref(`/users/${user}/matches`).set(matches)
// Will update specific children
firebaseApp.database().ref(`/users/${user}/matches`).update(matches)
Related
I am using cryptocomare API to get crypto coins data within a Nextjs App. What i doing is that when a user clicks on a perticular symbol, i redirect it to the coin details page where i try to extract the clicked symbol with getServerSideProps as follows and then dynamically put in the API call and send it to the API server.
`
export const getServerSideProps = async (context) => {
const res = await fetch(
`https://min-api.cryptocompare.com/data/pricemultifull?tsyms=USD&fsyms=${context.params.symbol}`
);
const icon = await res.json();
return {
props: {
icon,
},
};
};
`
This call returns a json object of nested objects and it goes to 2-3 levels deep. On Top it looks like following:
API call response
Inside my code, I want to access the data Object -> RAW -> (whatever the user clicked on). But, Since the Symbol or coin queried by the user is dynamic (means i can't predict what is clicked) I never know what to query. SO i tried this to access the data object.RAW[0]
In principal it should give me the whatever object is inside the object.RAW But it returns undefined
Can please someone guide me , how can i get the data inside object.RAW without knowing what is inside?
Thanks!
I have tried object.RAW[0] to access the data...,....
You can use Object.values(object.RAW) to get an array of the values inside RAW (assuming RAW is not undefined)
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
I have setup a Firebase Firestore Database and would like to filter it for a certain field value in a document.
I have a collection called "PRD" with thousands of documents where all contain the same fields. One of these fields a Document contains is a GTIN Number (String). I am receiving this Number from a Bar Code (called data), and would like to retrieve the Medication Name (called DSCRD, a different Field in all these Documents) using the GTIN Number scanned.
I am having difficulties with retrieving the Value from the Firebase and the documentation doesn't seem to get me any further. I have tried various retrieval methods. At the moment the code for retrieval looks like this:
import { dbh } from "../firebase/config"
import firestore from '#react-native-firebase/firestore'
dbh.collection('PRD')
.where('GTIN', '==', data)
.get()
.then(documentSnapshot => {
console.log('MedData',documentSnapshot.data())
});
I am unsure how to filter the right medicament using the GTIN provided by the Barcode scanner and then save the specific field value for the description of this medicament to a variable.
Firebase is setup correctly since I am able to write whole collections and documents in it.
Here is the database structure, as you can see there is the PRD Collection with all the medicaments and every medicament containing the GTIN and DSCRD Fields:
The problem with your implementation is that you are trying to call documentSnapshot.data() after querying a collection. This is the syntax you would use if you were fetching a single document. Your current query will return a list of documents which you need to handle like this:
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log('MedData', doc.data())
})
});
Assuming that the GTIN will fetch one unique document (will it?) then you can just use the only document returned by the query to get the name of the Medication like this:
var medName
dbh.collection('PRD')
.where('GTIN', '==', data)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log('MedData', doc.data())
medName = doc.data().DSCRD
})
});
I am currently working on a mobile app on React and I am having trouble understanding how to save a field from fire store that is an array.
Since I can't post images my database structure is all strings such as username, first name, etc but I have a field called follow list that is an array.
What I want to do is save the usernames from the following list into an array to later search fire store for the username's in the array, this is basically what I want to do so I can render my app's social Feed. I do know that I can probably create another subcollection and write something familiar to what I did to search for users but that was a QuerySnapShot which was overall documents not a specific one and I also know firebase creates an ID for arrays and it increases as the array gets bigger.
I do not want to end up making two more subcollections one for followers and following which I think not ideal right? My current approach is this
export const fetchUserFollowing = async (username) => {
const ref = firebase.firestore().collection('users').doc(username)
let results = []
ref
.get()
.then( doc => {
let data = doc.data()
results = data
})
.catch((err) => {
return 'an error has occurred ', err
})
}
From what I understand is that a DocumentSnapShot .get() function returns an object but what I want is to store follow list into results and then return that but I am not sure how to manipulate the object return to just give me follow List which is an array
https://rnfirebase.io/docs/v5.x.x/firestore/reference/DocumentSnapshot
link to docs
I am working on some Cloud functions that works with Firestore. I am trying to get a list of fields of a specific document. For example, I have a document reference from the even.data.ref, but I am not sure if the document contains the field I am looking at. I want to get a list of the fields' name, but I am not sure how to do it.
I was trying to use Object.keys() method to get a list of keys of the data, but I only get a list of number (0, 1...), instead of name of fields.
I tried to use the documentSnapShot.contains() method, but it seems doesn't work.
exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
if (event.data.exists) {
let myRef = event.data.ref;
myRef.get().then(docSnapShot => {
if (docSnapShot.contains('population')) {
console.log("The edited document has a field of population");
}
});
As the documentation on using Cloud Firestore triggers for Cloud Functions shows, you get the data of the document with event.data.data().
Then you can iterate over the field names with JavaScript's Object.keys() method or test if the data has a field with a simple array check:
exports.tryHasChild=functions.firestore.document('cities/{newCityId}')
.onWrite((event) =>{
if (event.data.exists) {
let data = event.data.data();
Object.keys(data).forEach((name) => {
console.log(name, data[name]);
});
if (data["population"]) {
console.log("The edited document has a field of population");
}
});
This is my current Firebase database configuration where I want to use username as key and CurrentUser.ID as the value.
I tried to use string interpolation but I got some error.
function updateExistingUserRoot(username) {
const { currentUser } = firebase.auth();
return (dispatch) => {
firebase.database().ref(`/ExistingUser`).push({
`${username}`: currentUser.uid
})
}
}
I understand firebase generates an unique key every time data is being pushed but I would like to stay with the current configuration.
Update 1
I have changed to using set but the error persists.
function updateExistingUserRoot(username) {
const { currentUser } = firebase.auth();
firebase.database().ref(`/ExistingUser`).set({
`${username}`: currentUser.uid
});
}
The error: expected property assignment.
For the configuration you want, you should rather be using set or update methods to save or update your data.
firebase.database().ref(`/ExistingUser`).set({
`${username}`: currentUser.uid
})
This way, your data gets saved in the username node which will be mapped with the user's uid.
Hope that helps!
If you want to create a user with a specific key, you should remove the push method (that creates a unique key) and use something like:
firebase.database().ref(`/ExistingUser` + userKey).set({
username: value...
});
Everything in Firebase is an url.
https://testxxx.firebaseio.com/xxx/ExistingUser
If you want to create a user with a key of KEY1 as a child at this location you would have:
https://testxxx.firebaseio.com/xxx/ExistingUser/KEY1
The answer given by the two gentlemen are correct but I had to tweaked a little bit to get it working.
Here's the code
firebase.database().ref(`/ExistingUser/${username}`).set({
userID: currentUser.uid
}).then(() => console.log('Set existing user done'))
.catch((error) => console.log(error.message))