Me Articles

How to create a new collection using Firestore v9

You're might - like me - already familiar with Firestore <=8, and you now want to try out the new features in v9. There has been made some clear changes, working with collections and documents.

When I saw the documents, how to migrate from 8 to 9:
https://firebase.google.com/docs/web/modular-upgrade#example_2_refactoring_a_function
I was still pretty confused. And for that reason, I will try to explain how I made it much more simple, with this small amount of codes.

Lets start with the firebase config file

/app/firebase/firebase.js

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
  databaseUrl: process.env.NEXT_PUBLIC_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_APP_ID,
  measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { db };

At first view, there isn't the biggest changes here, except the new function getFirestore.

Now to the main reason for this article, how to create your very first collection.
Below, I will make two examples with the same output, using v8 and v9

V8:

import { db } from "../../firebase/firebase";

const addDocument = () => {
  const collectionId = "my-collection";
  const docId = "my-document";
  const value = { versionUsed: "V8" };
  const ref = db.collection(collectionId).doc(docId);
  ref.set(value);
}

V9:

import { db } from "../../firebase/firebase";
import { setDoc, doc } from "firebase/firestore";

const addDocument = () => {
  const collectionId = "my-collection"
  const docId = "my-document"
  const value = { versionUsed: "V9" };
  setDoc(doc(db, collectionId, documentId), value);
}

I can't make it much more simple than that. And if we are having a look at those examples, I sadly prefer v8 the most.

Hope it did help you, creating your first collection using V9 🎉

Me Articles How to create a new collection using Firestore v9