I want to add an array of users as a collection to fire-store database here is my code and i think its suppose to be working but i get nothing in the firestore databse collections so what exactly should i do can anyone help me with this??
import { addDoc , collection , setDoc , doc , getDocs} from "firebase/firestore";
import { db } from "./config";
const Users = [
{
userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
username: "John",
fullName: "John John",
emailAddress: "[email protected]",
dateCreated: Date.now(),
},
{
userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
username: "John",
fullName: "John John",
emailAddress: "[email protected]",
dateCreated: Date.now(),
}]
Users.forEach(async (user) => {
try {
const docRef = await addDoc (collection(db , "users" , user.userId) ,{
userId: user.userId,
username: user.username,
fullName: user.fullName,
emailAddress: user.emailAddress,
dateCreated: user.dateCreated,
})
console.log("Document written with ID : ",docRef.id)
} catch(err){
console. Error("Error adding document ",err)
}
})
here is my firestore database :
import { initializeApp } from "firebase/app";
import { getStorage } from 'firebase/storage';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
export const app = initializeApp(firebaseConfig);
export const storage = getStorage();
export const db = getFirestore(app);
export const auth = getAuth();
2
Answers
You should not use
async
/await
within aforEach()
loop, see "JavaScript: async/await with forEach()" and "Using async/await with a forEach loop".You can use
Promise.all()
as follows:I think the path that you are giving it to set new users to the collection is not getting the id of the user so its not adding the doc
Do this and let firebase gives them a unique id
or could be also what Renaud said, maybe you havent set the rules to allow you to edit the database.