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!
Related
I've been trying to figure this out for hours and I just can't. I'm still a beginner with Node.js and Firebase. I need your help to be able to retrieve the tokens array in my "userdata" collection to Node.js and be able to use it to send notifications in the Cloud Function. So far this is what I've been working on. Here is what my database looks like:
The receiverId is gathered from when I have an onCreate function whenever a user sends a new message. Then I used it to access the userdata of a specific user which uses the receiverId as their uid.
In the cloud function, I was able to start the function and retrieve the receiverId and print the userToken[key]. However, when I try to push the token it doesnt go through and it results in an error that says that the token is empty. See the image:
Your help would mean a lot. Thank you!
newData = snapshot.data();
console.log("Retrieving Receiver Id");
console.log(newData.receiverId); //uid of the user
const tokens = [];
const docRef = db.collection('userdata').doc(newData.receiverId);
docRef.get().then((doc) => {
if (doc.exists) {
console.log("DocRef exist");
const userToken = doc.data().tokens;
for(var key in userToken){
console.log(userToken[key]);
tokens.push(userToken[key]);
}
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
//Notification Payload
var payload = {
notification: {
title: newData.sendBy,
body: 'Sent you a message',
sound: 'default',
},
data: {
click_action : 'FLUTTER_NOTIFICATION_CLICK',
route: '/telconsultinbox',
}
};
console.log("Sending Notification now.");
console.log(tokens);
try{
//send to device
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Notification sent successfully');
console.log(newData.sendBy);
}catch(err){
console.log(err);
}
I think you should avoid using for..in to iterate through an array (you can read more about it in this answer). Try one of these 2 options:
You could use forEach(), which is more elegant:
userToken.forEach((token) => {
console.log(token);
tokens.push(token);
});
for-of statement:
for(const token of userToken){
console.log(token);
tokens.push(token);
}
Also, I would consider renaming userToken to userTokens, since it should contain multiple values. Makes the code a bit more readable.
I'm running my db to verify if "id" is already in use, if not, i can do my register, else, i cant user this id and i have to try another.
code:
db.collection("places").get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
// console.log(doc.id)
db.collection("places").doc(doc.id).collection("Local").where("id", "==", id_user)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc2) {
//cpnj is already registred
if (doc2.exists) {
console.log("id already exist")
document.getElementById("preloader").style.display = "none";
alert("id in use, try another id");
} else{
//register the user
}
});
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
});
});
The problem is when id doesn't exist, the "else" inside the function is not "actived" because the Firebase condition".where("id", "==", id_user)" doesn't exist, so the query is not done.
How can i trigger this and after check that the "id" is not in use and proceed with registration?
Within a loop over a query snapshot, the document will always exist. If there are no results, the query snapshot will be empty and it'll right now simply not enter your forEach loop.
What you're looking for is whether the query snapshot has any results, which you can do with:
if (querySnapshot.empty) {
//register the user
} else{
console.log("id already exist")
document.getElementById("preloader").style.display = "none";
alert("id in use, try another 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());
});
my initial code for writing data is this
var Cloud = firebase.firestore();
Cloud.collection("IPA").doc("Allipas").set({
IPlist: "A;B;",
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
Then i want to merge new information into my Field
var Cloud = firebase.firestore();
Cloud.collection("IPA").doc("Allipas").set({
IPlist: "C;",
} , {merge : true})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
but it replaces the field with 'C' only and i cant see A & B
The merge: true option merges the fields you provide in the API call with the existing fields in the document. It does not merge a single value with the existing value of a field.
If you want to update an existing value of a field, you will have to first read the value of that field, then update it in your code, and finally write it back to the database.
This typically is done in a transaction to ensure nobody else can write conflicting updates at the same time. An example:
var docRef = Cloud.collection("IPA").doc("Allipas");
Cloud.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(docRef).then(function(doc) {
if (!doc.exists) {
throw "Document does not exist!";
}
var newIPlist = doc.data().IPlist + "C;";
transaction.update(docRef, { IPList: newIPList });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});
Note that Firebase recommends not using such composite value, or arrays, precisely for this reason: having to read the existing value before updating it reduces the scalability of your solution. Have a look at the documentation on working with arrays, list, and sets for alternatives.
Your merge can be change for update?
updteSomething() {
this.db.collection('IPA').doc(Allipas).update({
IPlist: ""A;B;C;",
})
.then(function () {
console.log("Document successfully deleted!");
}).catch(function (error) {
console.error("Error removing 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()
})
}