skip to Main Content

I have a cloud function in firebase emulator and I am trying to update an array. However when the function runs, I get the following error: TypeError: Cannot read properties of undefined (reading 'arrayRemove'). I’m not sure what is going wrong. My node version is 16.

This is my function code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

const db = admin.firestore();
const storage = admin.storage();

exports.completeEventRegistration = functions.firestore
    .document("<path>")
    .onCreate(async (snap, context) => {

     // <ommitted>

      try {

        await db.runTransaction(async (transaction) => {

          // <omitted>   

          const fieldValue = admin.firestore.FieldValue;

          transaction.update(committeeRef, {"countries": fieldValue.arrayRemove({
            "name": chosenCountry,
            "taken": false,
          })});


        });

      } catch (error) {
        console.log("Error registering: ", error);
        throw new functions.https.HttpsError("internal", "Error registering");
      }

    });

2

Answers


  1. Chosen as BEST ANSWER

    I fixed the issue thanks to this GitHub issue.

    Following is the fixed code:

    const
       { initializeApp } = require('firebase-admin/app'),
       { getFirestore } = require('firebase-admin/firestore');
    
    const IS_EMULATOR = ((typeof process.env.FUNCTIONS_EMULATOR === 'boolean' && process.env.FUNCTIONS_EMULATOR) || process.env.FUNCTIONS_EMULATOR === 'true');
    
    initializeApp();
    let firestore = getFirestore();
    
    if (IS_EMULATOR) {
       firestore.settings({
         host: 'localhost',
         port: '<firestore emulator port>',
         ssl: false
       })
    }
    
    transaction.update(committeeRef, {"countries": FieldValue.arrayRemove({
      "name": chosenCountry,
      "taken": false
    })});
    

  2. You need to declare fieldValue as follows, with require:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    
    const fieldValue = require('firebase-admin').firestore.FieldValue;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search