Firebase Giving Failed Precondition Error - javascript

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.

Related

Firebase Error "Uncaught Error in snapshot listener: FirebaseError: The query requires an index"

I'm getting the above error when I run the following query. I can visit the link provided to create an index, but if I understand this correctly I don't think that is feasible since the query is searching through the "members" map for the current users ID which will obviously change depending on the user. Is there some kind of workaround to this issue or would I need to restructure my database?
const subscribeChats = () => {
const chatsQuery = query(
collection(db, "chats"),
where(`members.${getAuth().currentUser.uid}.inChat`, "==", true),
where(`members.${getAuth().currentUser.uid}.isHidingChat`, "==", false),
orderBy("lastActive", "desc")
);
return onSnapshot(chatsQuery, (snapshot) => {
setChatsList(
snapshot.docs.map((doc) => {
return { id: doc.id, data: doc.data() };
})
);
});
};

A firestore query not working in react-native

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.

Firestore is running a query twice when I use query operators and the second time I get null as response

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

cannot do multiple query indexed firestore collection

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

algolia firestore function wont trigger

I've want to sync my Cloud Firestore with Algolia search index. I'm currently only able to deploy the firestore function, but it wont trigger onWrite or onChange.
I'm following this guide: Angular Full Text Search With Algolia Backend
As you can see the JS is deployed but it wont trigger when i add, remove or change a document in the database. The log don't show it either.
Database design:
-|search
-|searchId
-|id: string
-|name: sting
-|ref: string
Database rule:
//Search field
match /search/{searchId}{
allow read;
allow write: if request.auth != null;
}
JS function:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const algoliasearch = require('algoliasearch');
const algolia = algoliasearch(functions.config().algolia.appid, functions.config().algolia.adminkey);
exports.updateIndex = functions.database.ref('/search/{searchId}').onWrite(event => {
const index = algolia.initIndex('search');
const searchId = event.params.searchId
const data = event.data.val()
if (!data) {
return index.deleteObject(searchId, (err) => {
if (err) throw err
console.log('Search Removed from Algolia Index', searchId)
})
}
data['objectID'] = searchId
return index.saveObject(data, (err, content) => {
if (err) throw err
console.log('Search Updated in Algolia Index', data.objectID)
})
});
I was facing similar problem. Change those lines:
exports.updateIndex = functions.database.ref('/search/{searchId}')...
to
exports.updateIndex = functions.firestore.document('search/{searchId}')...
and
const data = event.data.val()
to
const data = event.data.exists ? event.data.data() : null;
and it should work. It worked for me but I am facing now
Function returned undefined, expected Promise or value
log error and can't solve it but function works.

Categories

Resources