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");
}
Related
I need to update on document on my subcollection but I have an error:
Error: [firestore/not-found] Some requested document was not found.
First of all selected the good document on my collection Teams:
firestore()
.collection("Teams")
.where("tokenTeam", "==", "gvb2j3pcm9")
.get()
.then(async (querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach(async (doc) => {
let Teams = doc._data;
console.log(Teams);
// code below fits in here
})
}
})
I have no error with the above code. Then I call my subcollection with just the statut in "attente" to select the one I want to update. My console.log(members) is working well.
After that I update the document selected I want to update which gives this error:
Error: [firestore/not-found] Some requested document was not found.
// insert into above code
doc.ref
.collection("membersList")
.where("statut", "==", "en attente")
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("no documents found");
} else {
querySnapshot.forEach((doc) => {
let members = doc.id;
console.log(members);
doc.ref
.collection("membersList")
.doc(members)
.update({
statut: "Validé",
});
});
}
});
This is my data model:
Did I forget something?
The problem is in the query you are making inside the querySnapshot.forEach. The doc.ref is representing a reference to the current document you are operating in the foreach, which is already a memberList document.
So what you are doing currently in your code is looking for the same document as a separate document in a subcollection contained in your original document, which won't work, in order to work all you have to do is this:
doc.ref
.update({
statut: "Validé",
});
If I understand correctly, this is your goal: For the given team token/ID, update all members who have a "statut" value of "en attente" to "Validé".
As #RafaelLemos stated in their answer, you only need to use doc.ref instead of doc.ref.collection("membersList").doc(members). This mistake was caused by you shadowing the variable named doc and is why you should name your variables appropriately.
Similar to this answer, you can search for requests the same way. As you find each document to update, rather than update it immediately as you have in your code, you should make use of a batched write to make a single atomic database write.
firestore()
.collection("Teams")
.where("tokenTeam", "==", "gvb2j3pcm9")
.get()
.then(async (matchingTeamsQuerySnapshot) => {
if (matchingTeamsQuerySnapshot.empty) {
console.log("no teams found");
return;
}
// start a batched write
const batch = firestore().batch();
// for each team found, find members with "statut" of "en attente",
// and queue updating "statut" to "Validé"
await Promise.all(
matchingTeamsQuerySnapshot.docs
.map(async (teamDocSnapshot) => {
// const teamData = teamDocSnapshot.data();
// console.log(teamData);
const memberRequestsQuerySnapshot = await teamDocSnapshot.ref
.collection("membersList")
.where("statut", "==", "en attente")
.get();
memberRequestsQuerySnapshot.forEach(memberRequestDoc => {
batch.update(memberRequestDoc.ref, {
statut: "Validé"
});
});
})
);
// update the database all at once
return batch.commit();
})
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);
});
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 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());
});
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);
});