[Firestore] orderBy stops onSnapshot from listening, order incorrect as well
Hey,
I'm noticing some odd behaviour with orderBy when used in conjunction with onSnapshot. Not sure if it's isolated to just using them together or not.
Here is my code:
this.unsubscribeChatsRef = this.chatsRef
.where(`users.${this.user.uid}`, '==', true)
.orderBy('lastMessage.order')
.onSnapshot((querySnapshot) => {
console.log('ListenForItems chat query', querySnapshot)
var listItems = [];
querySnapshot.forEach((doc) => {
listItems.push({
groupName: doc.data().groupName,
groupNameKey: doc.data().groupName.toLowerCase(),
groupChat: doc.data().groupChat,
docId: doc.data().docId,
lastMessage: doc.data().lastMessage,
users: doc.data().users,
createdAt: doc.data().createdAt,
});
this.setState({
data: listItems,
loading: false
})'
});
});
- I'm seeing that
orderByseems to be disablingonSnapshotfrom listening.
When I run the above code, it picks up all the data correctly on the first go around. But if I send any updates to the docs retrieved in the query, the data is not updated on the app end.
I then commented out .orderBy('lastMessage.order) and it works as intended. The listener is functioning and updating the data properly.
I'm seeing the following in adb logcat:, (i left out all the object data). Not sure it's relevant tho as I see it in both of the above cases:
10-31 13:26:13.108 3627 3627 W unknown:ReactNative: Calling JS function after bridge has been destroyed: RCTDeviceEventEmitter.emit(["firestore_collection_sync_event",{"querySnapshot":{"metadata":{"hasPendingWrites":true,"fromCache":false},"documents":[{"metadata":{"hasPendingWrites":false,"fromCache":false},"
- When I run the above code (with orderBy) the order of the docs is all wrong. I tested this by placing numbers going sequentially up in the
lastMessage.orderfield and it was incorrect when presented in the app. On both ascending and descending.
Environment
-
Application Target Platform: Both, but currently testing in Android
-
Development Operating System: Windows 10
-
Build Tools:
-
React Native version: 0.49.3
-
RNFirebase Version: 3.0.3 Updated to 3.0.6 no change
-
Firebase Module: Cloud Firestore
@rtman Sounds like a strange issue. You mention that the target platform is both, but you're currently testing in Android. Are you able to confirm whether this errant behaviour is the same on iOS too or it is just limited to Android?
@chrisbianca
No unfortunately, the eventual goal is iOS as well, but I am just testing on Android for now.
Hi @rtman,
My understanding is that your query is actually not valid in firestore unless you have an index on both 'users.uid' and lastMessage.order. See here https://firebase.google.com/docs/firestore/query-data/indexing
Peter
@peterdivvito
In the past when I've needed a composite index it tells me directly in the logcat, I didn't see that this time. However I'll give it a go! Not sure how I can set an index for the users.${this.user.uid} field though since it's dynamic.
@peterdivvito @chrisbianca
Ok so creating a composite index did indeed fix my ordering issue, but using orderBy is still killing the onSnapshot unfortunately. I wish there was a yellow box warning regarding the need to create a composite index.
Progress tho!
Let me know if I can provide additional info to help diagnose this.
@rtman I've just set up a test case for this in our test app, but am unable to reproduce the issue. Both iOS and Android are receiving events in onSnapshot when the data changes.
My test case is as follows:
Data setup:
const COL_1 = {
baz: true,
daz: 123,
foo: 'bar',
gaz: 12.1234567,
geopoint: new firebase.native.firestore.GeoPoint(0, 0),
naz: null,
timestamp: new Date(2017, 2, 10, 10, 0, 0),
};
const collectionTests = firebase.firestore().collection('collection-tests2');
await Promise.all([
collectionTests.doc('col1').set({ ...COL_1, foo: 'bar0' }),
collectionTests.doc('col2').set({ ...COL_1, foo: 'bar1', daz: 234, timestamp: new Date(2017, 2, 11, 10, 0, 0) }),
collectionTests.doc('col3').set({ ...COL_1, foo: 'bar2', daz: 345, timestamp: new Date(2017, 2, 12, 10, 0, 0) }),
collectionTests.doc('col4').set({ ...COL_1, foo: 'bar3', daz: 456, timestamp: new Date(2017, 2, 13, 10, 0, 0) }),
collectionTests.doc('col5').set({ ...COL_1, foo: 'bar4', daz: 567, timestamp: new Date(2017, 2, 14, 10, 0, 0) }),
]);
Test:
const collectionRef = collectionTests.orderBy('timestamp').endAt(new Date(2017, 2, 12, 10, 0, 0));
const newDocValue = { ...COL_1, foo: 'updated' };
const callback = sinon.spy();
// Test
let unsubscribe;
await new Promise((resolve2) => {
unsubscribe = collectionRef.onSnapshot((snapshot) => {
callback(snapshot.docs.map(doc => doc.data().daz));
resolve2();
});
});
callback.should.be.calledWith([123, 234, 345]);
const docRef = firebase.firestore().doc('collection-tests2/col1');
await docRef.set(newDocValue);
await new Promise((resolve2) => {
setTimeout(() => resolve2(), 5);
});
// Assertions
callback.should.be.calledWith([123, 234, 345]);
callback.should.be.calledTwice();
// Tear down
unsubscribe();
I just updated my test to use a complex field path, i.e. object.field just to rule that out and it still worked fine
@chrisbianca
Looks ok, your test setup is bit confusing me to me but I get what is going on.
One thing I notice is that you are testing with .endAt(new Date(2017, 2, 12, 10, 0, 0) which I am not. Is using endAt required when using orderBy?
Also my orderBy was after a where, I wonder if that would make a difference.
I'll have another go at debugging this issue in the next day or two but please let me know if I can provide more detail on how to figure this out, I'm kind of at a loss right now.
@chrisbianca I have another section in my code that is actually working with orderBy and onSnapShot. It is as follows:
this.unsubscribeListenForItems = this.chatsRef
.doc(this.chat.docId)
.collection('messages')
.orderBy('order')
.onSnapshot((snapshot) => {
...
}
The difference being that this does not use where. Can you re test with a where query followed by orderBy and onSnapShot to see if you can reproduce the issue?
I'm seeing the same behavior when using a combination of where/orderBy/limit, onSnapshot is not being called. It works when I remove the orderBy clause.
@chrisbianca Have you had a chance to review my feedback? Seems like this is a real issue now that there is another user experiencing the same issue.
Me too, I have the same issue when using combination where/orderBy/onSnapshot
me too. I don't know why just removing orderBy and it work. Adding orderBy just make thing worst.
this.unsubscribe = dbFireStore.collection('room').where('user_id.'+user_id,'==',true).orderBy('last_update','desc')
.onSnapshot((querySnapshot)=>{
});
The answer to this seems to be addressed on this page.
https://firebase.google.com/docs/firestore/query-data/order-limit-data
However, if you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field:
@peterdivvito
I'm not using a range comparison just '=='. So that shouldn't apply?
Had tried on using get(). This is not working as well. According to @peterdivvito, it should be for range comparison only. but not like below using '=='.
dbFireStore.collection('room').where('user_id.'+global.obj_user.user_id,'==',true).orderBy('last_update').get().then((qs)=>{
console.log(qs);
});
I'm seeing this behavior on iOS as well. The onSnapshot function is called initially for all the results that currently exist in firestore, but when a new value is added it does not get called again. Here's the code that I'm using.
const app = firebase.app();
const userId = app.auth().currentUser.uid;
app
.firestore()
.collection("entries")
.where("userId", "==", userId)
.orderBy("dateCreated")
.onSnapshot(snapshot => {
// handle change
});
I have verified that when I remove the .orderBy("dateCreated") portion the onSnapshot function is called as expected and get's live updates as data is added. But then I need to sort client side which would be less than ideal with large data sets.
FYI: AFAIK the where and orderBy has to be on same key. Source: https://firebase.google.com/docs/firestore/query-data/order-limit-data#order_and_limit_data Check the bottom most code example
Please check and close this issue, if you find it correct. cc @chrisbianca
@priyankinfinnov
It says this is specifically for non equal comparison (range comparison).
However, if you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field
My original issue is with an equality comparison.
@Salakar @chrisbianca
Can you guys weigh in on this issue please?
If you could provide a reproducible code + data sample then that'd be super helpful. Currently we've been unable to reproduce this issue.
cc @chrisbianca