I know this is a very basic question, but I am new to reactjs and firebase. After two days I am giving up on searching for an answer myself.
I have a firestore database 'MusicList' containing several documents. Within these documents the field 'seperatedStrings' holds (you'll probably will be guessing it) artists and titles of songs.
image of the firestore database
How do I retrive the value a single field (in this example 'seperatedString') using the ID (in this example '5ajnHZ8YDaiYvTAvJ1ec'?
Whenever I am querying for this:
firestore().doc("MusicList/" + "5ajnHZ8YDaiYvTAvJ1ec").seperatedString
the console claims that it is "undefined" (That is a lie!), I'd expect 'Phil Upchurch Blackgold'
Thanks in advance.
You are not using Firebase queries correctly. If you want to fetch a document from a collection, you would do so like this:
firebase
.firestore()
.collection('MusicList')
.doc('5ajnHZ8YDaiYvTAvJ1ec')
.get()
.then(doc => {
if (doc && doc.exists) {
const { separatedString } = doc.data();
//use separatedString
}
});
Check out Firestore - Get A Document for more information.
Also, it would probably be better to structure your documents differently. You could have an artist and track field, and use doc.data().artist and doc.data().track respectively.
Related
I am handling some documents with firebase realtime database. I need to delete a document that I don't have the access to read it client side via SDK. In order to do that I need to know what is the id, so I should store it in my db (mongo) and when I need to delete a document on firebase I just get it from my DB and the I delete it.
I took a look to this answer but it doesn't work for me.
I insert documents into my firebase DB with this method (server side using firebase-admin)
const writeNotification = (uid: string, notification: INotification) => {
const db = admin.database();
const notsRef = db.ref(`notifications/${uid}`);
notsRef.push({
..._.omit(notification, 'to'),
});
};
If I do notsRef.id I get undefined.
How can I get the ID of my document that I have just inserted?
p.s. my documents are organized like this:
The answer you are looking at is about Firestore and not Realtime Database that you are using. The Reference has a key property and not id:
console.log('New Key', notsRef.key)
// to get child node's key
const childNotesRef = notsRef.push({
..._.omit(notification, 'to'),
});
console.log(childNotesRef.key)
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 have a database in Google cloud firestore with a collection of documents that each includes the following parameters:
country, headline, URL, date.
I need to return two separate things depending on the input in Dialogflow. The first thing is the headlines of the 3 latest news and the second thing is the headlines of the 3 latest news in France.
I am to do it in Dialogflows inline editor, which is javascript, but it doesn't seem entirely the same as javascript e.g. in Node.
I have already solved the first problem with the following code:
function TopNews_Global(agent) {
agent.add('Here are the latest Global news');
let documents = db.orderBy('Date', 'desc').limit(3);
return documents.get()
.then(snapshot => {
snapshot.forEach(doc => {
agent.add('-' + doc.data().Headline + '.');
agent.add('Link:(' + doc.data().URL + ')');
});
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
Where db is my collection in firebase.
The following code is my solution to the second thing I want to return, and this is where I am stuck. It is not possible to filter and order over two different fields as I do. But there MUST be a way around this - it's a pretty simple thing I wanna do.
https://firebase.google.com/docs/firestore/manage-data/export-import
function TopNews_France(agent) {
agent.add('Here are the latest French news');
let documents = db.orderBy('Date', 'desc').where('Country', '==', 'France').limit(3);
return documents.get()
.then(snapshot => {
snapshot.forEach(doc => {
agent.add('-' + doc.data().Headline + '.');
agent.add('Link:(' + doc.data().URL + ')');
});
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
Assuming that as you state, db is a collection object, your query is a valid one for Firestore.
db.orderBy('Date', 'desc').where('Country', '==', 'France').limit(3);
Firestore does allow queries across multiple fields, assuming that the only orderBy or range queries are on the same field. Thus, your query is valid (one orderBy and one non-range where on different fields).
You didn't mention what error you are getting, but I suspect it is this (nominally visible in a Javascript console):
The query requires an index. You can create it here: (url)
That is because this is a query which requires a composite index -- it sorts on one field and filters on another.
Thus, to fix this, you just need to create the index. In an ideal case, you can just click on the URL in that error message and be brought to the exact point in the Firebase console to create the exact index you need. If for some reason you need to create it manually, you can also do that through the console. After it completes building, your query should work.
In this case, you will need to create an index for whatever collection db is pointing at, with the fields Date (in descending order) and Country (in either descending or ascending order -- the equality won't care), and with collection scope.
How to get all the books of a specific author from my database?
Here is a snapshot of my database, i want to get "Colson Whitehead"
for web development, javascript.
To get all books by author Colson Whitehead, you do a query like this:
var query = firebase.database().ref("books").orderByChild("author").equalTo("Colson Whitehead");
query.on("value", function(snapshot) {
snapshot.forEach(function(bookSnapshot) {
console.log(bookSnapshot.key+": "+bookSnapshot.val());
});
})
This callback will get called initially and then every time something about the books by Colson Whitehead changes. If you only want the initial call, use once instead of on.
I'm trying to retrieve a single document from a collection. I'm now using the code below that returns a collections of items, but I know that there is only one item. So it ain't that clean.
Setup:
private db: AngularFirestore
private itemSubs: Subscription[] = [];
itemAd= new Subject<Item>();
fetchItemFromDatabase(itemId: string) {
this.itemSubs.push(
this.db.collection('items', id => id.where('itemId', '==', itemId)).valueChanges().subscribe((items: Item[]) => {
this.itemAd.next(items);
}));
}
I tried to do it with this.db.collection('items').doc(itemId).get() , but I'm getting an error on get() that it's not found/supported. I also didn't got autocompletion when trying to call this methode (methode found in the official cloud firestore documents).
I looked at around at some other solutions and then tried it with this.db.collection('items').doc(itemId).ref.get().then(...) , but here I got an empty doc back.
So I'm a bit stuck at the moment and I don't want to use that whole collections logic when I know there is only 1 item in it.
There may be multiple documents with itemId equal to a given value. While you may know that there is only one in your app, the database and API cannot know nor enforce that. For that reason the query you run will always return a query snapshot that potentially contains multiple documents.
this.db.collection('items', id => id.where('itemId', '==', itemId))
If you want to enforce that there is only one document with the given item ID, consider using that item ID as the document name instead of storing it as a field in the document.
There can be only one document with a given name, so that means the ID is guaranteed to be unique. And you can then retrieve that document with:
this.db.collection('items').doc(itemId)