如何在Firestore中正确使用arrayUnion?

use*_*470 2 javascript node.js express firebase google-cloud-firestore

我正在尝试使用 Node.js Firebase Admin SDK 将新的 javascript 对象添加到 Firestore 集合中的数组字段。

我确信我所针对的文档具有相关字段,但我不断收到错误:TypeError:

Cannot read property 'arrayUnion' of undefined

我知道这个问题,但修复没有帮助。

非常感激任何的帮助。

有问题的路线:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 6

该错误告诉您fbApp.firestore.FieldValue未定义。因此,它没有任何属性或方法供您调用。

如果您想使用FieldValue,则必须通过firebase-admin命名空间导入来引用它,而不是通过初始化的应用程序实例。

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

// now you can write FieldValue.arrayUnion(...)
Run Code Online (Sandbox Code Playgroud)