2

I am trying to add a new javascript object to an array field in a Firestore collection using the Node.js Firebase Admin SDK.

I am certain that the doc that I am targeting has the field in question but I keep getting the error: TypeError:

Cannot read property 'arrayUnion' of undefined

I am aware of this question but the fix does not help.

Any help would be most appreciated.

Route in question:

router.post("/create-new-user-group", async (req, res) => {
  try {
    const { userId, usersName, groupName } = req.body;

    if (!userId || !usersName || !groupName) return res.status(422).send();

    const groupRef = await db.collection("groups").doc();

    const group = await groupRef.set({
      id: groupRef.id,
      name: groupName,
      userId,
      members: [{ id: userId, name: usersName, isAdmin: true }],
    });
    
    const response = await db
    .collection("users")
    .doc(userId)
    .update({
      groups: fbApp.firestore.FieldValue.arrayUnion({
        id: userId,
        name: userName,
      }),
    });


    res.send(group);
  } catch (error) {
    console.log("error creating new group:", error);
    res.status(400).send(error);
  }
});

firebaseInit.js:

const admin = require("firebase-admin");
const serviceAccount = require("../serviceAccount.json");

const firebaseApp = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://xxx-xxxxx.firebaseio.com",
});

exports.fbApp = firebaseApp;
user8467470
  • 780
  • 3
  • 10
  • 25

1 Answers1

6

The error is telling you that fbApp.firestore.FieldValue is undefined. So, it doesn't have any properties or methods for you to call.

If you want to use FieldValue, you will have to refer to it via the firebase-admin namespace import, not through an initialized app instance.

const admin = require("firebase-admin");
const FieldValue = admin.firestore.FieldValue;

// now you can write FieldValue.arrayUnion(...)
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441