where and orderBy - Firebase conflict - javascript

I'm using react firebase hooks and trying to query by using orderBy and where selectors.
I'm not getting any error, just empty records. Here's a code:
const queryRef = query(
getFromFirestore("/clients"), // My custom db/config getter
orderBy("archived"),
where("archived", "==", false),
orderBy("createdAt", "desc"),
limit(5)
);
const [clients = [], loading, error] = useCollectionData(queryRef, {
snapshotListenOptions: { includeMetadataChanges: true },
});
Everything is ok until I'm using where and orderBy together. If I'll remove one of those - then firebase returns me the correct records
I've used the suggestion from this post: Using where and orderby with different parameter firebase javascript - but it still not working.
EDIT: Here's a screen from DB

I've found a solution. I dint know that error object can contains such an info - about wrong query or something around query. Anyway - firestore throws this error:
FirebaseError: The query requires an index. That index is currently building and cannot be used yet. See its status here:
Rest of error message is an exact link to our firebase console/config where you can add almost automatically - missing index. Google Cloud needs some time to build and index. After this time - everything works well.
The thread can be closed.

Related

'RestConnection Commit failed with error' when trying to write to firestore

I am getting the following error when trying to write to Firestore. This is done in JavaScript(React).Can anyone tell what is this and how can I fix this?
#firebase/firestore: Firestore (8.3.1): RestConnection Commit failed with error: {"code":"failed-precondition","name":"FirebaseError"} url: https://firestore.googleapis.com/v1/projects/{project name}/databases/(default)/documents:commit request: {"writes":[{"update":{"name":"projects/{project name}/databases/(default)/documents/teams/T22yKl1ERQSlfuZNitrvs2vRjSJ2/team-analytics/T22yKl1ERQSlfuZNitrvs2vRjSJ2-Dec-22-2021","fields":{"homePageViews":{"integerValue":"3"},"timeModified":{"timestampValue":"2021-12-22T09:32:00.000000000Z"}}},"updateMask":{"fieldPaths":["homePageViews","timeModified"]},"currentDocument":{"updateTime":"2021-12-22T09:23:08.916511000Z"}}]}
My code that is trying to access Firestore is shown below:
return db.runTransaction(async (transaction) => {
const analyticsDoc = await transaction.get(analyticsReference);
if (analyticsDoc.exists) {
const analytics: any = analyticsDoc.data();
return transaction.update(analyticsReference, { homePageViews: analytics.homePageViews + 1, timeModified: getCurrentDateTime() });
}
const newAnalytics: AnalyticsObject = {
totalViews: 0,
homePageViews: 1,
timeModified: getCurrentDateTime(),
};
return transaction.set(analyticsReference, newAnalytics);
});
I am also getting the following error in my console:
POST https://firestore.googleapis.com/v1/projects/optimx-sports/databases/(default)/documents:commit 400
Edit: After more digging in, I am thinking it might be because I am sending 2 transactions to the same document simultaneously. Is it possible that this error is because of this?
Below are a few Points you can check with:
In Cloud Firestore, you can only update a single document about once
per second, which might be too low for some high-traffic
applications. Have a look at Firestore documentation.
You can refer to the Documentation.
Also You can try with Postman API to access data.
Another way is combining two commits as well.
The issue was that I was sending two transaction commits to one firestore document within a second. The second commit was raising the above error. Fixed it by combining the two commits

Have an empty docs in querySnaphsot when trying to get data with firebase

I recently developped a firebase schedule function to retrieve data on every monday.
I tested it during the previous days and it was working correctly. However, this morning, I discovered that my query wasn't able anymore to retrieve data as it used to do. I now have an empty array at QuerySnapshot.docs. You can find my code below:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.scheduledFunction = functions.pubsub.schedule("0 0 * * 1").onRun(async () => {
console.log("start");
const querySnapshotnext = await db.collection("Next_challenges").orderBy("createdAt").get();
console.log("Let see querySnapshot :", querySnapshotnext); //it works, I can see QuerySnapshot object
console.log("Let see docs :", querySnapshotnext.docs); //have an empty array [] even if it should not, it wasn't empty few days ago
console.log("let see the data of the first doc : ", querySnapshotnext.docs[0].data()); //is of course undefined
return null;
});
You can find my database below with the doc that is normally selected:
The rules of my databases are the following :
I don't really understand why my code isn't working anymore, I think it's certainly related to some parameters stuffs and don't really know how I could debug this by myself so don't hesitate to give me some tips so I can be more autonomous with firebase. Thank you :)
Firestore's documentation has a note that says,
An orderBy() clause also filters for existence of the given field. The result set will not include documents that do not contain the given field.
You have .orderBy("createdAt") in your query but there isn't any createdAt field in the documents (at least the one in screenshot). Did you change your document structure recently that is causing this issue?
Also the Admin SDK bypasses any security rules so I'd recommend setting them to false if you don't need to access data directly from client.

Query documents in firestore from an array of ID's

I was wondering how I can query documents from a firestore collection from an array of ID's? I only want the documents in the collection that are in the array of ID's. I looked at another answer and think my approach is correct, however, I am getting an error.
(node:15105) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined
> at /Users/username/SideProjects/projectname/functions/index.js:40:38
> at processTicksAndRejections (internal/process/task_queues.js:95:5)
The error happens because the function is not finding any documents in the collection from that array of ID's. However, I double-checked the database and know that there are documents in the collection with ID's from the array.
const admin = require('firebase-admin')
....
let feedItems = db.collection(feedItemsCollection)
feedItemsList = feedItems.where(admin.firestore.FieldPath.documentId(), 'in', ['HPOorsSnbHpTYwwXxfWw']).get().then(snapshot2 => {
console.log(admin.firestore.FieldPath.documentId())
console.log("In feed Items")
//console.log(feedItemIds)
console.log(snapshot2[0])
//error happens on this line because snapshot2[0] returns undefined
console.log(snapshot2[0].data())
})
Snapshot2[0] returns undefined which I'm assuming means that no data was returned. I think I'm not properly calling documentId(), but don't know the fix.
There "maybe" two problems with your code. Follow both points to make sure things are working
Data inside snapshot2 maybe empty
You'll first have to fix your code to test this theory. You're not accessing data from snapshot2 correctly. To do it right, one way is this:
// `snapshot2` will have a `docs` property that you can leverage
const snapshot2Data = snapshot2.docs.map((doc) => doc.data());
.documentId() may not be doing what it's supposed to (as you said)
To test this theory, check if snapshot2Data is empty. Run :
console.log(snapshot2Data); // what do you get ?
If no, it's not empty and you got data back, then you're all set. Nothing more to do
If yes, it is empty, then run :
console.log(admin.firestore.FieldPath.documentId()); // what do you get ?
Did you get back a string? If no, then we have another problem. You'll need to take a closer look at your firebase-admin setup, as well.

Trying to get a snapshot of a variable from firebase gives me an error

Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})

Firebase Firestore: orderBy combined with where causes error "Operation was rejected"

I am looking at the Firebase Cloud Firestore documentation for orderBy. When I try to execute this
var facultyQuery = facultyRef.where("department", "==", "Core Teacher").orderBy('bb_last_name', 'desc');
I get the error:
Error: Firestore: Operation was rejected because the system is not in a state required for the operation`s execution. (firestore/failed-precondition).
Both of these simpler cases work just fine:
var facultyQuery = facultyRef.orderBy('bb_last_name', 'asc');
var facultyQuery = facultyRef.where("department", "==", "Core Teacher");
But when I combine the where and the orderBy, something I have done before with other Firestore collections, it fails.
Here is a sample record:
Tip for anyone that needs it,
If you've forgotten to create an index and are getting the above error, run adb logcat and then attempt to load the data again - it usually gives you a URL link which will very kindly create the required index for you.
I encountered this same issue, and Frank van Puffelen's comment fixed it for me. You need to create a composite index for "department" and "bb_last_name". Since "department" uses the equality operator, it doesn't matter whether it is ascending or descending in your index.

Categories

Resources