Cloud Firestore collections queries not working - javascript

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);
});

Related

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());
});

Perform a simple select query in Firebase Firestore

How can I perform a simple search in Firebase Firestore to check if a record exists in a collection? I've seen this code in the documentation, but it is not complete.
// Create a reference to the cities collection
var citiesRef = db.collection('cities');
// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');
In my use case I want to check the rejected contacts collection for a given number. This is my code
const collectionRef = db.collection('rejectedContacts');
const queryRef = collectionRef.where('contact','==',phone);
let contactRejected: boolean = queryRef.get.length>0 ;
if (contactRejected) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
}
I've checked the function with a rejected number, which i added manually in the collection, but it is not responding with the rejected message. How can I get the count or the row itself with a select query. What is wrong with my code?
UPDATE 1
As #Matt R suggested, I updated the code with this
let docRef = db.collection('rejectedContacts').where('contact', '==', phone).get();
docRef.then(doc => {
if (!doc.empty) {
return response.json(
{
status: 0,
message: `Contact , ${phone} is blocked. Please try again with another one.`,
result: null
});
} else {
return response.json(
{
status: 0,
message: `Contact , ${phone} is not blocked`,
result: null
});
}
})
.catch(err => {
console.log('Error getting document', err);
});
But when checked with the existing number, it is returning with not blocked
Edit 2
return collectionRef.select('contact').where('contact', '==', phone).get()
.then(snapShot => {
let x : string = '['
snapShot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
x+= `{${doc.data}},`;
});
return response.send(x);
});
It is only returning the value of x from this line
let x : string = '['
Firestore's get() method returns a promise and response, I would try in this format to handle whether the document exists or not. This format may also lend better error messages when troubleshooting.
EDIT / UPDATED: Using the where clause returns a snapshot that must be iterated through, because it can return multiple documents. See documentation here: https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection
Updated code with your example.
var collectionRef = db.collection('rejectedContacts');
var query = collectionRef.where('contact','==',phone).get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});

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.

firebase / firestore docs queries Not working - javascript

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()
})
}

Categories