so i tried to get data from firebase using this function
getData(){
const startDate = this.$store.state.inputFilter.rangeDate.start
const endDate = this.$store.state.inputFilter.rangeDate.end
db.collection(this.inputType)
.where('idAlat', '==',this.equipment)
.where('tanggal', '>=', startDate).where('tanggal', '<=', endDate)
.where('project', '==', this.project)
.get().then(docs => {
docs.forEach(doc => {
console.log(doc.data().tanggal.toDate(), doc.data().idAlat)
})
})
}
but then every time i try to run the fucntion, it shows error like this in console:
but then i follow the link and do the instruction to create composite index in firebase like this:
Is there something wrong i did? Thanks!
PS: word 'tanggal' means 'date' in english
Related
I am using react-native and I want to get specific data so I used a query, the problem is that it didn't work, but if I remove the where and do an if statement it works. How can I fix this ?
This is my implementation:
let query = firestore().collection('conversations');
query = query.where('users', 'array-contains', myId);
// query = query.where('postId', '==', postId);
query
.orderBy('timestamp', 'desc')
.limit(limit)
.get()
.then((snapshot) => {
const offersObjects = {};
if (snapshot.docs.length) {
snapshot.docs.forEach((doc) => {
if (postId === doc.data().postId) {
offersObjects[doc.id] = { ...doc.data(), pendingMessages: [] };
}
});
dispatch({
type: chatTypes.SET_OFFERS,
payload: { offers: offersObjects },
});
}
})
Where the code is commented is where this query doesn't work which is weird since the one above it works fine. How can I fix this ?
If you have more than one condition on a query, it may need a composite index that is not automatically created. If that is the case, executing the query (e.g. by calling get() on it) will raise an error, but you'r not hancling errors. I recommend adding a catch clause after your then and logging the error.
If the problem is caused by a missing index, the error message contains a URL that opens the Firebase console on the page to create the exact index that is needed, with all fields already filled in. Create the index, wait for it to be completely created, and run the query again.
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
I want to get from firestore all the documents in a collection ("invitations") where the date is equal or greater than today at 00:00:00 and some other parameters.
My function is:
var today_init = new Date()
today_init.setHours(0, 0, 0, 0)
let query = await db.collection("invitations")
.where("date", ">=", today_init)
.where("sender.user_uid", "==", Fire.user.uid)
.where('data.is_here', '==', false)
query.onSnapshot(async (querySnapshot) => {
try {
console.log(querySnapshot)
//more code here....
}catch(error){
console.log(error)
}
What is happening is that it runs twice automatically, the first execution it returns the firestore documents that I want, and the next execution it returns null.:
So, obviously the first response is the one that I want, but I don't know why is running twice or what is really happening but that null value ruins my logic.
When I comment the line:
.where("date", ">=", today_init)
The query runs perfectly. The think is that I don't want the old invitations.
PS. I'm using react-native
After a while I came up with this:
await db.collection("invitations")
.where("date", ">", today_init)
.where("sender.user_uid", "==", Fire.user.uid)
.where("data.is_here", "==", false)
.orderBy("date", "desc")
.onSnapshot((querySnapshot) => {
console.log(querySnapshot)
}, function (error) {
console.log(error)
})
The error callback function helped me to create the index.
More info : https://firebase.google.com/docs/firestore/query-data/listen#handle_listen_errors
Am getting the ff error with the ff code:
Error:
{"code":"failed-precondition","name":"FirebaseError","__zone_symbol__currentTask":{"type":"macroTask","state":"notScheduled","source":"setTimeout","zone":"angular","cancelFn":null,"runCount":0}}
My Code:
getOldPosts(forum_id: string, user_id: string, start_key?: string): Promise<Posts[]> {
return new Promise((resolve, reject) => {
let olderPosts: Posts[] = [];
let _5daysAgo = this.dateTime.getFiveDaysAgoDate();
const postsRef = this.afirestore.collection<Posts>('posts').ref;
const query = start_key == undefined || start_key == null
? postsRef.where('createdDate', '<=', _5daysAgo).where('forumId', '==', forum_id).where('memberId', '==', user_id)
: postsRef.where('createdDate', '<=', _5daysAgo).where('forumId', '==', forum_id).where('memberId', '==', user_id).startAt(start_key).limit(50);
query.get().then(
res => {
res.docs.forEach(doc => {
olderPosts.push(doc.data() as ForumPosts);
});
resolve(olderPosts.reverse());
},
err => {
reject(err);
}
);
});
}
I can't seem to figure out why this is happening. I've tried searching on google but I dont seem to find a solution. What am I doing wrong ?
Thanks.
According to Firestore's documentation in the Manage indexes page
If you attempt a compound query with a range clause that doesn't map
to an existing index, you receive an error.
You can use the Firebase Firestore web console to create the indexes manually for your query.
Otherwise, just run the query and it will throw an error with a URL to the Firestore console where you will get the option to automatically create this compound index.
postsRef.where('createdDate', '<=', _5daysAgo).where('forumId', '==', forum_id).where('memberId', '==', user_id)
The code block looks like the culprit because it has an equality clause combined with a range clause.
Where is my call wrong? The first console.log leads to the role object and the second console.log leads to undefined. When it should be the user.
componentDidMount(){
let user = fire.auth().currentUser;
let db = fire.database();
let roleRef = db.ref('/roles');
roleRef.orderByChild('user').equalTo(user.uid).once('value', (snapshot) => {
console.log(snapshot.val())
console.log(snapshot.val().user);
})
}
Result:
Firebase:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code doesn't take the list into account. The easiest way to do so is with Snapshot.forEach():
roleRef.orderByChild('user').equalTo(user.uid).once('value', (snapshot) => {
snapshof.forEach((roleSnapshot) => {
console.log(roleSnapshot.val())
console.log(roleSnapshot.val().user);
});
})