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.
Related
constructor(props) {
super(props);
this.state = {
users:[]
};
}
//method to get the data from users collection
async componentDidMount() {
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
}
this function returning an empty error
i want to print list of users uid
here i have users collection and inside it i have retailers collection and its document
One thing you have to realize here is that your users collection contains no documents. The document IDs are shown in italics, which means that there is no document here. The IDs are visible because there is a nested subcollection under each document. They are shown like this in the console so that you can click through and navigate to the nested subcollection, despite the document being missing.
If you want to list users with a query, you will have to actually create documents in the users collection. They can be empty if you don't have any information. But you do need actual documents in the users collection in order for anything to show up in a query.
This line in your current code querySnapshot.docs.map(doc => doc.data()) takes the data of each document. But you're keeping the UID in the ID of each document, so you'll want to use:
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.id);
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
Update: As Doug pointed out in his answer, if there are no actual user documents, your get() call will not return it.
I highly recommend creating user documents, even if it's just an empty one.
For now, the only way to get the UID would be to load all retailers for all users, and then use those results to get the ID of the parent documents:
const db = firebase.firestore();
db.collectiongroup("retailers")
.get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log("retailed "+doc.id+" for user "+doc.ref.parent.parent.id);
});
})
.catch( err =>{
console.log(err);
});
You'll have to deduplicate the UIDs, but that will leads to getting the UIDs.
But you'll be loading all retailers for all users this way, so as said, I highly recommend storing a small/empty user document instead.
The data method on querySnapshot.docs gets the data now to get the id of each document you need to add access the id property as UID is stored in id property
async componentDidMount() {
const db = firebase.firestore();
db.collection("users")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data().id);
console.log(data);
this.setState({ users: data });
})
.catch( err =>{
console.log(err);
});
}
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!
I'm trying to get data from my database hierarchy db.collection/doc/collection/
I need to get the data from the collection "product"
I can already filter out the right document, by using this snippet.
Still, didn't manage to get any data from the next collection.
db.collection('deliveryservice').where('owner_id', '==', user.uid).collection('product').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
Please try the following way to retrieve data from your product collection.
var docRef = db.collection("deliveryservice").doc(user.uid).collection('product');
docRef.get().then((snapshot) => {
snapshot.docs.forEach(doc => {
}
}).catch(function(error) {
console.log("Error getting document:", error);
})
As firestore is new, i am having problems using it.
I have to get Collection of all users and traverse it. But it is not working.
db.collection("users").get().then(function(querySnapshot){
console.log(querySnapshot.data());
});
It says:
querySnapshot.data is not a function
And following code:
callFireBase(mobileToCheck){
db.collection("users").where("mobile_no", '==', mobileToCheck).get().then(function(querySnapshot){
if (querySnapshot.exists) {
var userData = querySnapshot.data();
var userId = querySnapshot.id;
console.log(mobileToCheck + "Exist In DB");
}else{
console.log(mobileToCheck + "Do Not Exist In DB");
}
});
}
Is always printing
923052273575 Do Not Exist In DB
Even if it exists, See following image for reference. In docs they have told this (i have used) way.
It looks that tou want to call.data() on collection of documents, not one document. Please see if this code works:
db.collection("users").get().then(function(querySnapshot){
querySnapshot.forEach(doc => {
console.log(doc.data());
});
}).catch(err => {
console.log('Error getting documents', err);
});
You should use docs.map then doc.data(). Here is how to do it with Firestore using async await syntax
import firebase from 'react-native-firebase'
async fetchTop() {
const ref = firebase.firestore().collection('people')
const snapshot = await ref.orderBy('point').limit(30).get()
return snapshot.docs.map((doc) => {
return doc.data()
})
}
As Cloud Firestore is new, I am having problems using it.
I have to get Collection of all users and traverse it. But it is not working.
db.collection("users").get().then(function(querySnapshot){
console.log(querySnapshot.data());
});
It says:
querySnapshot.data is not a function
And following code:
callFireBase(mobileToCheck){
db.collection("users").where("mobile_no", '==', mobileToCheck).get().then(function(querySnapshot){
if (querySnapshot.exists) {
var userData = querySnapshot.data();
var userId = querySnapshot.id;
console.log(mobileToCheck + "Exist In DB");
}else{
console.log(mobileToCheck + "Do Not Exist In DB");
}
});
}
Is always printing
923052273575 Do Not Exist In DB
Even if it exists, See following image for reference.
I think you have some things confused as querySnapshot doesn't have data, but it does have docs which have data.
In your first example, you are asking it to return all documents in the collection. You'll want something like this instead:
db.collection("users").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
});
Key difference is looping over the docs in querySnapshot and console logging the data from each doc.
For your second example, you'll want to check if the querySnapshot is empty, rather than checking if it exists.
db.collection("users").where("mobile_no", "==", mobileToCheck)
.get()
.then(function(querySnapshot) {
if (querySnapshot.exists) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
var userData = doc.data()
var userId = doc.id
console.log(mobileToCheck + "Exist In DB");
});
} else {
console.log(mobileToCheck + "Do Not Exist In DB");
};
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});