firebase.firestore() shows bizarre data and not my actual documents from the database/ - javascript

I am querying firebase firestore by...
let database = firebase.firestore();
let places = database.collection("place");
console.log("places", places);
now the logged data is bizarre and not the actual documents..
here is a picture of the log...can you please advice regarding tackling this ?

If you want to retrieve all items in your collections called "place" you can do something like this:
let database = firebase.firestore();
let places = database.collection("place");
const querySnapshot = places.get()
// You can make an empty array to eventually push the items into
const collectionArray = []
querySnapshot.forEach((doc) => {
const data = doc.data()
collectionArray.push(data)
}).catch(function(error) {
console.log("Error getting documents: ", error);
})
console.log('collectionArray:',collectionArray)
}

Your code hasn't actually executed any query yet. All it's done is build a Query object.
If you want to execute the query, call get() on it, and handle the results as shown in the documentation.
let database = firebase.firestore();
let query = database.collection("place");
query.get()
.then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
console.log("document", documentSnapshot.data());
})
})

Related

Display user data with post data in one flatlist. Merge two Firebase firestore collections into one end result

I have a post feed combining of two firebase firestore collections.
userPosts = [] // collectionGroup() query of all users images
users = {} // the users data after for looping posts results
I'm currently getting both the posts from the post collection and the users data from the users collection after for looping the post uids.
This is working fine and shows the user object combined with the post object in the console.log() but It will not show in the flatlist when combining this end result to a state hook!
Basically, it seams to be working fine but I can't display it. I need the end result to be the post with the users data retrieved after for looping.
Again, console.log shows correct merge of data, attaching to state hook and displaying in flatlist is not working.
My code:
useEffect(() => { // showGlobal feed
if (showGlobalFeed) {
firebase.firestore()
.collectionGroup("userPosts")
.orderBy("creation", "asc")
.get()
.then((snapshot) => {
let posts = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
const uid = data.uid;
return { id, uid, ...data }
})
for(let i = 0; i< posts.length; i++){
firebase.firestore()
.collection("users")
.doc(posts[i].uid)
.get()
.then((snapshot) => {
if (snapshot.exists) {
let user = snapshot.data();
user.uid = snapshot.id;
// the below cosloe.log works fine.
console.log('\nFOR LOOP COMBINED ==========> \n',[posts[i], user])
// the hook fails to display combined data correctly
setGlobalPosts([posts[i], user])
}
else {
console.log('does not exist')
}
})
}
// console.log({...posts})
})
}
}, [showGlobalFeed])
Flatlist = data={globalPosts}

Cloud firestore not ordering problems when query

My query it's not ordering. Actually it doesn't response. I receive an empty results screen when trying with this:
let stateQuery = firestore.collection('categories').where('user', '==', uid).orderBy('name');
stateQuery.onSnapshot((querySnapshot) => {
const docs = [];
querySnapshot.forEach((doc) => {
docs.push({ ...doc.data(), id: doc.id });
});
setCategories(docs);
});
};
I tried also to do this, and nothing:
let stateQuery = firestore.collection('categories').where('user', '==', uid);
let stateQuery2 = stateQuery.orderBy('name');
The issue is that your query requires a Composite index. Documentation on composite indexes is on this page.
Check the console for an error message which should include the link necessary to create the composite index. When I run a similar query on my database, I get this link
https://console.firebase.google.com/v1/r/project/(PROJECTNAME)/firestore/indexes?create_composite=Xd1.....XTY

Firebase Cloud Firestore Read-Write Data

i am trying to signup and save user info into firestore. Save operation is fine but i want to search that info but nothing happening. Here is my code
Signup
firestore
.collection("users")
.doc(user.userId)
.collection("profile")
.add({ ...user })
.then(() => {
auth.onAuthStateChanged((u) => {
if (u) {
u.updateProfile({
displayName: user.displayName,
});
}
});
});
Fetch All users data
firestore
.collection("users")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
//doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
You should be able to achieve by using a similar code as the below one. It very similar to yours, but with some differences, where we separate the referencing to the database and let the querySnapshot iterates by itself, so the data can be returned. I usually use this format to return data from collections.
var db = admin.firestore()
var usersReference = db.collection("users");
usersReference.get().then((querySnapshot) => {
querySnapshot.forEach((userDoc) => {
console.log(userDoc.id)
var userDocData = userDoc.data()
console.dir(userDocData)
})
})
This should work, so, in case it doesn't return anything, probably your saving opearation is not working properly. This will return both the user's id and the whole data from it.

Update data using firestore cloud function

I need help, i'm trying to update my comments collections using cloud function, but my code doesn't seem to work. My function succesfully run but doesn't update my avatarUrl when my userPhotoUrl is update
Here the whole path of the collection that i want to update : "/comments/{postId}/comments/{commentId}"
my firestore collection
exports.onUpdateUser2 = functions.firestore
.document("/users/{userId}")
.onUpdate(async (change, context) => {
const userUpdate = change.after.data();
const userId = context.params.userId;
const newPhotoUrl = userUpdate.photoUrl;
console.log("userId",userId);
console.log("newPhotoUrl",newPhotoUrl);
const querySnapshot = await admin.firestore().collection("comments").get();
querySnapshot.forEach(doc => {
console.log("doc",doc.data());
const postId = doc.id;
const comments = admin.firestore().collection("comments").doc(postId).collection("comments").where("userId","==",userId).get();
comments.forEach(doc2 => {
return doc2.ref.update({avatarUrl: newPhotoUrl});
});
});
});
Thank you,
UPDATE
I try to change the code, by using then to deal with these various promises but i don't really know why commentsRef.get() seem to return me empty querySnapshots, because the comments collections in my firestore database have multiple documents where in each documents there is a another comments collections where in this seconds comments collections there is a bunch of documents containing data. With this whole path i don't know how to iterate until being in the documents containing the data that i need to update. Can someone help me please ?
exports.onUpdateUserUpdateComments = functions.firestore
.document("/users/{userId}")
.onUpdate(async (change, context) => {
const userUpdate = change.after.data();
const userId = context.params.userId;
const newPhotoUrl = userUpdate.photoUrl;
console.log("userId",userId);
console.log("newPhotoUrl",newPhotoUrl);
const commentsRef= admin.firestore().collection("comments");
return commentsRef.get().then(querySnapshot => {
return querySnapshot.forEach(doc => {
return admin
.firestore()
.collection("comments")
.doc(postId)
.collection("comments")
.where("userId", "==", userId)
.get()
.then(doc => {
if (doc.exists) {
doc.ref.update({avatarUrl: newPhotoUrl});
}
return console.log("The function has been run.");
});
});
});
});
Without trying it, it should be something like this:
return admin.firestore().collection("comments")
.doc(postId)
.where("userId", "==", userId)
.get()
.then(doc => {
if (doc.exists) {
doc.ref.update({avatarUrl: newPhotoUrl});
}
return console.log("The function has been run.");
});
Regardless, following Doug Stevenson's advice, you shouldn't start learning JS in Cloud Functions, as those nested loops are a bit strange and you may lack a good starting point for learning.

Using forEach with single document queries in Firestore?

How should I write a query for Firestore when I know that the number of document references returned will be only 1?
const query = firebase.firestore().collection('Users').where('mobile', '==', '<some mobile number>').limit(1);
To get the document from this query, I'm using the forEach loop. Is there any way to get the document and its data without using the loop?
let docId;
query.get().then((snapShot) => {
snapShot.forEach((doc) => {
docId = doc.id;
});
if(docId) {
// doc exists
// do something with the data...
}
}).catch((error) => console.log(error.message));
OK. I figured it out.
The .docs() method can be used on the snapShot object to get an array of all the documents refs matching the query.
So, if I only have a single document, I can simply access it as follows:
query.get().then((snapShot) => {
const doc = snapShot.docs[0];
const docId = doc.id;
const docData = doc.data();
// so stuff here...
}).catch((error) => console.log(error.message));

Categories

Resources