I have not been able to find a reference in the documentation on how to get a document reference when you know the id of it in firebase.
I am passing the id to a webpage to lookup a QR code. Rather than storing a secondary unique id for each qrcode document I am relying on the firebase unique id.
Here is the lookup I tried but which seems to fail.
firebase.firestore().collection('cues').doc(id).get().then(function (docsnapshot) {
console.info('About: ' + docsnapshot.get('text'));
});
I was able to get my original code to work with this modification to the query
firebase.firestore().collection('cues').doc(id).get().then((doc) => {
... and then just use doc.get("field") to get values form my document
you can access to data like this:
const { id } = docsnapshot
const data = docsnapshot.data()
const myDoc = { id, ...data }
myDoc.text
myDoc.anything...
Related
I'm struggling to formulate a supabase db query from multiple tables, whilst using a value from a URL.
I have 3 tables (simplified)...
series > id, series
authors > id, name
books > id, title, series_id(fk), authors_id(fk)
I want to get a list of books in a series, along with the author and series name from the following URL...
app.com/series. i.e. app.com/harrypotter
I can get the series name using getServerSideProps, but struggling how to write my query to supabase. Every way I write it either gives me a NULL object or a 500 error.
I feel like I should be querying the books table and then be able to get the series and author names through the foreign keys. But the query that it's centred around is the series name, which is in the series table. So unsure of the db query to do it, or whether I should structure my db table's in a different way?
export async function getServerSideProps( context ) {
const { series } = context.query;
...
return {
props: {
...
}
};
}
Thanks for any help in advance!
Please ensure you have foreign keys set up, and then you can use Supabase to query foreign table examples (SQL join).
There needs to be more data to give an exact answer, but here are the relevant docs.
Supabase get a single record
Supabase select - not super obvious, but you need to click the button Query foreign tables
Supabase filters
I also included logs and a try/catch so you can see your exact errors and where your code is failing.
const Page = (props) => {
console.log(props)// logged to browser's console
return <>Your page<>;
}
export async function getServerSideProps( context ) {
try {
const { series } = context.query;
console.log("series", series); // ensure series is present and check if is an object
const { data, error } = await supabase.from('series')
.select(`
id,
title,
book (
title // you can also use `*` check out select all docs
author (
name
)
)
`)
.eq('id', series)
.limit(1)
console.log("error", error);
console.log("data", data);
return {
props: {
series: data
}
}
} catch (e) {
console.log(e);
}
}
export default Page;
Note: getServerSideProps logs will show up in your server's console (where you run npm dev) - not the browser's console. You should remove the console logs once you figure out what's happening.
I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});
I have a list of a document ids and I want to fetch the data of those documents from Firestore and display it using the FutureBuilder.
contestList = [awebnmsdfjkeeer23,324cdas4asdf, 34sdfasgadsg]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document('$element')
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
}).then((value) => {});
});
print(joinedContests);
}
}
I have used the above function to get the data and try to store in the list, like one document data in list. But i am getting the blank list of the data. How to get the whole document and display it using the FutureBuilder in flutter
It looks like you have multiple different issues on your code:
contestList has invalid keywords. 324cdas4asdf and 34sdfasgadsg are not valid variable names as they both start with a number, which is not a valid variable name. If they are supposed to be the ids that you want to retrieve they must be enclosed by ", which will make them strings.
You are trying to access the document using '$element' as if it were a bash variable, but there are two problems there: it's not done like that and there no need to do it. element already holds the value as a string so it just has to be accessed as is.
You are calling the method then twice without doing anything the second time. This shouldn't be a concern, but it simply doesn't do anything and can me omitted.
Below you will see an edited version of your code fixing all the aforementioned mistakes.
contestList = ["awebnmsdfjkeeer23", "324cdas4asdf", "34sdfasgadsg"]
Future<void> fetchUsergameData() async {
contestList.forEach((element) async{
await Firestore.instance.collection('LiveGames').document(element)
.get().then((dss) {
if(dss.exists) {
tempgame.add(dss.data["GameData"]);
temproom.add(dss.data["Room"]);
temptitle.add(dss.data["Title"]);
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
}
});
});
print(joinedContests);
}
}
On another note, it's unknown to us the type of tempgame, temproom and temptitle but judging by how you are accessing it you may simply want to do something like this:
tempgame = dss.data["GameData"];
temproom = dss.data["Room"];
temptitle = dss.data["Title"];
temp = tempgame + temproom + temptitle;
joinedContests.add(temp);
I'm trying to get the data of the column name. I have the table users and inside it has the columns name, email and phone_number
The code below is what I used to take the table users and the key or the id of the row. This is almost identical to the delete code where I use ref('users/'+key).remove() for that matter
async print(key) {
console.log(firebase.database().ref('users/'+key))
}
I expect the output of name for example 'John'
What you are getting is the reference.
You need to do .once('value') to get a snapshot at that reference, then do .val() on that snapshot to get the data
async print(key)
{
const name = await firebase.database().ref('users/'+key).once('value')
console.log(name.val()))
}
I was integrate firebase with ionic3 angularjs, adding data successfully like
var fireData =
{
userid : '1122233',
questionId : '18022',
answerId : '25633',
points : '2'
}
//Add
this.sample.list('paperCode').push(fireData);
Now I want to update like below mentioned image
If you don't know the key, first query the data with the field you know then iterate through the result and get the key. Then you can perform update.
Try
updateFunction(questionId){
this.sample.list('/paperCode', ref => ref.orderByChild('questionId').equalTo(questionId)).snapshotChanges()
.subscribe(actions => {
actions.forEach(action => {
// here you get the key
console.log(action.key);
this.sample.list('/paperCode').update(action.key, { points: 10 });
});
});
}
I hope your question id is unique, otherwise it will override all queried results.
You need to set a path to that object and update the field you would like. In this example...
firebase.database().ref(1710172911409/L5F4BEuePS8qxUqDNoF/questionId).update("NEWQUESTIONID);
If you don't know the unique id of the pushed object, you can query for it. Learn more here