I use Firebase to develop a web app. I got this error message
Uncaught TypeError: firebase.firestore(...).collection(...).orderBy(...).limit(...).set is not a function
at HTMLButtonElement.<anonymous> (main.js:152)
because of this code.
firebase.firestore().collection('script').orderBy('timestamp','desc').limit(1).set({
finaltext: resultText.value,
name: firebase.auth().currentUser.displayName,
uid: firebase.auth().currentUser.uid
},{merge: true}).catch(function(error){
console.error('Error writing new message to Firestore', error);
});
I searched the Internet, but couldn't find why this error message occurred. Could you give me any advice, please?
The method limit
returns a value of type Query
:
limit
limit ( limit: number ): Query < T >
Creates and returns a new Query that only returns the first matching documents.
https://firebase.google.com/docs/reference/js/firebase.firestore.Query#limit
Therefore both orderBy
and limit
are used when you want to retrieve data. If you want to add data to the database then just do the following:
firebase.firestore().collection('script').set({
finaltext: resultText.value,
name: firebase.auth().currentUser.displayName,
uid: firebase.auth().currentUser.uid
},{merge: true}).catch(function(error){
console.error('Error writing new message to Firestore', error);
});
You need to first fetch the desired document, with get()
, before writing the new field(s) with set()
(with merge option) or update()
.
firebase.firestore().collection('script').orderBy('timestamp','desc').limit(1).get()
.then(querySnapshot => {
if (!querySnapshot.empty) {
//We are sure the document exists, we can then use update()
return querySnapshot.docs[0].ref.update({
finaltext: resultText.value,
name: firebase.auth().currentUser.displayName,
uid: firebase.auth().currentUser.uid
});
} else {
throw new Error("No document");
}
})
.catch(error => {
console.log("Error:", error);
});
Note that the get()
method returns a QuerySnapshot
, so you need to do querySnapshot.docs[0]
to get the DocumentSnapshot
corresponding to the unique doc returned by the query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.