Home > other >  I've got stuck with Firestore Functions Batch Writing
I've got stuck with Firestore Functions Batch Writing

Time:10-10

What I want: every time a new user is created, let's grab his restaurants and put them into a restaurant collection, and inside that, create a document with the restaurant's name and put the user's other restaurants inside that

=> why? so this way I can see which restaurants are connected via a user.

The code is listed below. It doesn't work, this is what I get in the Logs Explorer: "FirebaseError: Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"

Is this how batch writing should be done? I've looked up on that error message, and as far as I understood it using "doc" from firestore should solves it, so I'm bit lost here because that's what I'm doing.

import * as functions from 'firebase-functions';
import { doc, writeBatch } from '@firebase/firestore';
import * as admin from 'firebase-admin';
import { credentials, privateDatabaseURL } from './config/firebase';

admin.initializeApp({
    credential: admin.credential.cert({
        privateKey: credentials.private_key,
        projectId: credentials.project_id,
        clientEmail: credentials.client_email,
    }),
    databaseURL: privateDatabaseURL,
});

exports.writeToFirestore = functions.firestore
    .document('users/{user_name}')
    .onWrite((change, context) => {
        const data = change.after.data();

        if (!data) {
            return null;
        }

        const db = admin.firestore();

        const restaurants = data.restaurants;
        // @ts-ignore
        const batch = writeBatch(db);

        for (let i = 0; i < restaurants.length; i  ) {
            const rest = restaurants[i];
            // @ts-ignore
            const restRef = doc(db, 'restaurants', rest);

            for (let j = 0; j < restaurants.length; j  ) {
                const rest2 = restaurants[j];

                if (rest === rest2) {
                    continue;
                }

                batch.set(
                    restRef,
                    {
                        restaurants: rest2,
                    },
                    { merge: true }
                );
            }
        }

        return batch.commit();
    });

CodePudding user response:

It seems that you have two instances of the Firestore class in your code, and they're not compatible. It's hard to say where this problem is coming from, as I don't know which line is failing. But a simple fix is to not create a second Firestore instance, and instead grab it from the change object that functions passes to your code:

To do that, change:

const db = admin.firestore();

To:

const db = change.after.ref.firestore;
  • Related