Retrieving single firestore doc in angular - javascript

I want to retrieve and display a single doc from a collection when I click on a view link. At the moment I get routed to the view page successfully but unable to display the properties of the doc I want. Here's the code I'm working with
schedule.service.ts
getSchedule(id: string) {
return this.afs
.collection("schedules")
.doc(id)
.ref.get()
.then(function(doc) {
doc.data();
console.log(doc.data()); //i see the data logged on my console correctly
});
}
then in the view.component.ts file
ngOnInit() {
this.scheduleDetail();
}
scheduleDetail() {
const id = this.route.snapshot.paramMap.get("id");
console.log(id); //I see the doc id correctly
this.schedule = this.scheduleService.getSchedule(id);
console.log(this.schedule);//I can't see the correct doc data
}
console.log(this.schedule) does not log the correct data like console.log(doc.data()) in the service.ts file does. Instead I see this
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
What is the right way of getting the doc data from my service into my component?

You have to fix with a correct usage of promise:
getSchedule(id: string) {
return this.afs
.collection("schedules")
.doc(id)
.ref.get()
.then(function(doc) {
return doc.data(); // here...
});
}
and
scheduleDetail() {
const id = this.route.snapshot.paramMap.get("id");
console.log(id);
this.scheduleService.getSchedule(id).then(data => {
console.log(data); // ... and here
});
}

Related

Firebase get document collection based on specific field using angular

I want to get collection data based on UserId field .
getData(){
const data$ = this.fbs.collection(this.trackerData,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotChanges().subscribe(res=>{
console.log(res);
});
}
if i get data like this i am getting response as :-
but i need response data like :-
You need to transform your stream to get what you want:
getData(userId: string){
return this.fbs.collection(
this.trackerData,
ref=> ref.where('UserId','==',userId)
).snapshotChanges().pipe(
map(action => {
const data = action.payload.data();
const id = action.payload.id;
return { id, ...data };
})
);
}
getData("WrKDk0XSNjU20FI0EVRvADzvNHz1").subscribe(res=> console.log(res));

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!

File metadata is not getting updated in Firestore Storage

I have created a Cloud Function that trigger on any new file upload in Firebase Storage. Once successful upload function will update its metadata, but even though setting new metadata with 'setMetadata()' is not getting applied. There is no error during the process and but on checking for updated metadata, the new one is not reflecting.
exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {
const storageRef = admin.storage().bucket(object.bucket);
var metadata = {
'uploader': 'unknown'
}
await storageRef.file(object.name).setMetadata(metadata).then(function(data) {
console.log('Success');
console.log(data);
return;
}).catch(function(error) {
console.log(error);
return ;
});
return;
});
There is no error, and on Cloud Function log its printing 'Success' message. Also "metageneration: '2'" property also got updated, which means it should have updated metadata with new values, but it didn't.
The problem comes from the fact that if you want to set custom key/value pairs they must be in the metadata key of the object you pass to the setMetadata() method, i.e. the metadata object in your case. This is explained in the API Reference Documentation for node.js.
So the following will work:
exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {
const storageRef = admin.storage().bucket(object.bucket);
var metadata = {
metadata: {
'uploader': 'unknown'
}
}
try {
const setFileMetadataResponse = await storageRef.file(object.name).setMetadata(metadata);
console.log('Success');
console.log(setFileMetadataResponse[0]);
return null;
} catch (error) {
console.log(error);
return null;
}
});

Get Cloud Firestore database collection

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

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