Firestore how to get keys from firestore document - javascript

Using below query, I can get the document and doc.data().name to get the value for the key 'name'. I would like to get all the keys in that document. How can I get that?
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
//**I want to get all keys in the document here.**
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

Based on my example from this answer, you can do:
docRef.get().then(function(doc) {
if (doc.exists) {
let json = doc.data();
console.log("Document data:", json);
console.log("Document keys:", Object.keys(json));
Object.keys(json).forEach((name) => {
console.log(name, json[name]);
});
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

In firebase, If you want to access the value of a key in a document inside your collection. Let's say key "name" or "email". Use the code below:
searchSnapshot.docs[index]["name"].data()
searchSnapshot.docs[index]["email"].data()
Note: I used search box here, you might have a different plugin to implement.

Related

How to check if current user has filled out a document?

I have two collections, one is users and the other is invoice details. On user login, I need to check that the current user has filled out all fields in the invoice details collection. So need to show an alert as soon as user logs in to say to fill out details.
Both collections have the same UID's
checkJob = () => {
firebase.firestore().collection('invoice_details').where("accountname", "==", "").get().then((resultSnapShot) => {
if (resultSnapShot.size == 0) {
Alert.alert("Details need to be updated")
} else {
Alert.alert("Details ok")
}
})
}
If your invoice document generate after user submit some data then you can check if document exists of that user.
var docRef = db.collection("invoice_details").doc(userId);
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

get collection of documents with firestore

I was following this example:
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
// this is not working
const people = doc.collection("people");
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
I want to return an array of people within the city of SF.
According to https://firebase.google.com/docs/database/web/structure-data
when you fetch data at a location in your database, you also retrieve all of its child nodes.
but I canĀ“t find the right to return the collection within a doc (without making a new query)
In Firestore when you retrieve the data, you retrieve all the fields inside a document. If you want to retrieve data from another document or from subcollection then you need to do a different query.

Cloud Firestore can not find custom document id

This function is returning false if i try to get the custom document id.
It is only returning true when I enter document id on the firebase console.
checkDot() {
this.db.firestore.collection(this.DOT).doc(this.DOT).get()
.then( doc => {
console.log('Data is ', doc.exists);
if (doc.exists) {
// this.isDotExist = true;
console.log(doc, 'Colection exists');
}
else {
// new Account Create
console.log('Colection doos not exist');
this.presentConfirm();
}
});
This function stores user input in the database
async createNewAccount() {
// Binding data from user input
const { Company, Fname, Email, Password } = this;
try {
// creating user account
const res = await this.afAuth.auth.createUserWithEmailAndPassword(Email, Password).then(cred => {
// DOT value passed by another page, others from user input
this.db.collection(this.DOT).doc(this.DOT).collection(Company).doc(Fname).set({ Name: Fname });
});
this.showAlert('Succes', 'You have successfully registered!');
this.route.navigate(['']);
console.log(res);
} catch (err) {
this.showAlert('Error', err.message);
// console.dir(err);
}
}
As you can check in this question from the Community Query Firebase Firestore documents by the ID, there is a special method that you can use query via documentId. The method is this: 'FieldPath.documentId()'
Another reference is the official documentation Execute Query, where you can find the following example of code that you can use as a start point, to return documents via ID.
db.collection("collection").where("document", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
Besides that, there is the below question from the Community with more information and examples, related to a similar to yours, that might help you.
How to perform collection group query using document ID in Cloud Firestore
Let me know if the information helped you!

Retrieveing data from document of a collection in firestore database with document ID

I want to make a chat application with chat room by implementing firebase friendly chat app. I want to get all the information from "rooma" documentid of message collection. But i am not able to get the information from the document with ID "rooma" but i can access all the information from "message" collection.
my code is:
function loadMessages() {
// Create the query to load the last 12 messages and listen for new ones.
var query = firebase.firestore()
.collection('messages').where(firebase.firestore.FieldPath.documentId(), '==', 'rooma').get()
.orderBy('timestamp', 'desc')
.limit(12);
// Start listening to the query.
query.onSnapshot(function(snapshot) {
snapshot.docChanges().forEach(function(change) {
if (change.type === 'removed') {
deleteMessage(change.doc.id);
} else {
var message = change.doc.data();
displayMessage(change.doc.id, message.timestamp, message.name,
message.text, message.profilePicUrl, message.imageUrl);
}
});
});
}
my database structure is:
Imgur
If you want to get the data of "the document with ID 'rooma'", just do as follows, according to the documentation:
var docRef = db.collection("messages").doc("rooma");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
If you want to use onSnapshot(), in order to "listen to a document", you just have to do as follows, according to the documentation:
var docRef = db.collection("messages").doc("rooma");
docRef.onSnapshot(function(doc) {
console.log("Current data: ", doc.data());
});

Can I query a nested document value in firestore?

I'm looking to do a search on the following data in firestore:
Collection->Document->{date{month:10,year:2017}}
var ref = db.collection(collection).doc(document)
ref.where('date.month', '==', 10).get().then(doc=>{
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
}).catch(err => {
console.log('Error getting document', err);
});
The above pseudo code does not work. Any suggestions?
It looks like you are querying a document:
var ref = db.collection(collection).doc(document)
In stead you should be querying your collection:
var ref = db.collection(collection)
Your query will pick up all documents, which meet "date.month==10" criteria among array of documents in your collection.
Also I think you have to change how you parse the data coming from .get() because it's going to be an array:
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
This link should be also helpful to get the idea.

Categories