I’m trying to insert a document in an existing collection in my Firestore DB, i tried every solution suggested but still not working…
Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow write, read: if true; // temporary rule to allow all writes
}
}
}
Firebase Config file:
import { initializeApp } from "firebase/app";
import { getFirestore } from '@firebase/firestore'
import { getStorage } from 'firebase/storage'
const firebaseConfig = {
apiKey: process.env.FIREBASE_APIKEY,
authDomain: process.env.FIREBASE_AUTHDOMAIN,
projectId: process.env.FIREBASE_PROJECTID,
storageBucket: process.env.FIREBASE_STORAGEBUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGINGSENDERID,
appId: process.env.FIREBASE_APPID,
measurementId: process.env.FIREBASE_MEASUREMENTID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
const storage = getStorage(app);
export { db, storage }
My Insert Function:
async function insertDoc() {
const data = { name: 'John Doe', email: '[email protected]' };
const myCollectionRef = collection(db, 'restore');
await addDoc(myCollectionRef, data)
.then((docRef) => {
console.log('Document written with ID: ', docRef.id);
})
.catch((error) => {
console.error('Error adding document: ', error);
});
}
How my Firestore DB looks like:
I tried insertDoc()
function i created, and i expected data to be inserted to my Firestore DB.
2
Answers
I figured it out! I downgraded to Firebase version 7.24.0 and updated my code to match the version (app initialization, syntax...) and now it works perfectly!
I can see that you’ve tried using the official doc of firestore however you mixed it up a little bit.
In your insert function, you are using await which is the right way to add premises (More info here).
However, you’re also using .then() which is used to add premises for a fetch() for example. You will have for a fecth() :
In an async function the best way to add premises is :
You can find more information in the official doc but be careful when you select a version, you have to click on "Web version 9" as it seems that you’re using this version of firestore