Learn how to model Firestore relationships with a step-by-step guide on one-to-one, one-to-many, and many-to-many patterns using Firebase.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Setting Up Firebase Project
google-services.json file for Android or GoogleService-Info.plist for iOS and place it in the appropriate directory of your application project.
Step 2: Designing the Data Model
Understand Firestore’s Structure
Firestore is a NoSQL database that stores data in documents, which are organized into collections. Each document contains a set of key-value pairs and each document is identified by a unique ID.
Modeling One-to-One Relationships
Suppose you have two collections, Users and their Profiles. Each user has one profile.
In Users collection, store a reference to the corresponding Profiles document.
```json
{
"userId": "abc123",
"profileRef": "Profiles/profileId123"
}
```
Modeling One-to-Many Relationships
Suppose, each User can have multiple Posts.
Embed Post IDs within each user document, or keep Post documents in the Posts collection with a userId field.
```json
{
"userId": "abc123",
"posts": ["postId1", "postId2"]
}
```
Or in separate collection with reference:
```json
{
"postId": "postId1",
"userId": "abc123",
"content": "This is a post"
}
```
Modeling Many-to-Many Relationships
For example, Users and Groups, where each user can be in multiple groups and vice versa.
Use sub-collections or embedding arrays of references:
In Users:
```json
{
"userId": "abc123",
"groups": ["groupId1", "groupId2"]
}
```
In Groups:
```json
{
"groupId": "groupId1",
"members": ["userId1", "userId2"]
}
```
Step 3: Writing Data with Relationships
Add a Document with a Reference
Import necessary modules and write data to Firestore with JavaScript SDK.
```javascript
import { doc, setDoc } from "firebase/firestore";
// Reference to a user
const userRef = doc(db, 'Users', 'userId123');
await setDoc(userRef, {
profileRef: 'Profiles/profileId123'
});
```
Add Documents with Sub-collections
For Posts sub-collection under Users.
```javascript
import { collection, addDoc } from "firebase/firestore";
// Reference to posts sub-collection
const postsRef = collection(db, 'Users/userId123/Posts');
await addDoc(postsRef, {
content: 'This is a user post'
});
```
Step 4: Reading Data with Relationships
Retrieve a Document with a Sub-collection
Retrieve the user document and associated posts sub-collection.
```javascript
import { collection, getDocs } from "firebase/firestore";
// To get posts for a specific user
const querySnapshot = await getDocs(collection(db, 'Users/userId123/Posts'));
querySnapshot.forEach((doc) => {
console.log(${doc.id} => ${doc.data()});
});
```
Retrieve a Document with References
Fetch a user and then fetch the profile document by its reference.
```javascript
import { doc, getDoc } from "firebase/firestore";
const userRef = doc(db, 'Users', 'userId123');
const userSnap = await getDoc(userRef);
if (userSnap.exists()) {
const profileRef = doc(db, userSnap.data().profileRef);
const profileSnap = await getDoc(profileRef);
console.log('Profile:', profileSnap.data());
}
```
Step 5: Updating Relationships in Firestore
Update a Simple Field or Reference
Use the updateDoc method to update a reference or field in your document.
```javascript
import { updateDoc, doc } from "firebase/firestore";
const userRef = doc(db, 'Users', 'userId123');
await updateDoc(userRef, {
profileRef: 'Profiles/profileId456'
});
```
Handling Arrays in Firestore
Firestore supports operations like arrayUnion and arrayRemove for handling array fields.
```javascript
import { updateDoc, arrayUnion, doc } from "firebase/firestore";
const groupRef = doc(db, 'Groups', 'groupId1');
await updateDoc(groupRef, {
members: arrayUnion('userId3')
});
```
Step 6: Deleting Relationships
Delete a Sub-collection Document
To delete a document within a sub-collection, use the deleteDoc method.
```javascript
import { doc, deleteDoc } from "firebase/firestore";
await deleteDoc(doc(db, 'Users/userId123/Posts', 'postId456'));
```
Remove a Reference from a Document
Either update the field to null or use arrayRemove on an array of references.
```javascript
import { updateDoc, arrayRemove, doc } from "firebase/firestore";
const userRef = doc(db, 'Users', 'userId123');
await updateDoc(userRef, {
groups: arrayRemove('groupId1')
});
```
By following these steps, you can effectively model and manage relationships in Firestore. Understanding and properly designing your data model is crucial to optimize both the performance and scalability of your application.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.