node.js - 如何在 Firebase Firestore 中使用 arrayUnion() 将对象推送到数组中?

标签 node.js firebase express google-cloud-firestore

我当前的文档如下所示:

{
    "assignmentName": "OS Assignment-2",
    "dueDate": "10 August",
    "createdAt": "2020-08-02T20:27:28.916Z",
    "maxMarks": 10,
    "facutyName": "Dr. Muskan Gupta",
    "semester": "3",
    "submittedBy": [
        {
            "studentName": "Test name",
            "downloadUrl": "URL"
        },
        {
            "downloadUrl": "URL3",
            "studentName": "Test name2"
        },
        {
            "downloadUrl": "https://downloadthisfile.com",
            "studentName": "Nakshatra Saxena"
        },
        {
            "studentName": "Hello Bortehr",
            "downloadUrl": "httpsav"
        }
    ],
    "program": "CSE",
    "subject": "Operating System with UNIX"
}

我想在“submittedBy”字段中推送一个对象,但出现错误。我现在使用的代码是:

const submittedAssignment = {
    studentName: req.body.studentName,
    downloadUrl: req.body.downloadUrl,
    };
    admin
        .firestore()
        .collection("assignments")
        .doc(req.params.assignmentId)
        .update({
          submittedBy: firebase.firestore.FieldValue.arrayUnion(submittedAssignment)
        });
    })
    .then(() => {
      return res
        .status(201)
        .json({ message: `Assignment submitted successfully` });
    })
    .catch((err) => {
      console.error(err);
      res.status(500).json({ error: `Error submitting assignment` });
    });

但是我收到了这个错误

Error: Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore document. Couldn't serialize object of type "FieldValueDelegate" (found in field "submittedBy"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

最佳答案

您正在混淆 Firestore SDK。如果您使用 Admin SDK 进行更新,您还需要使用 Admin SDK 指定 FieldValue 类型值。

而不是这个:

      submittedBy: firebase.firestore.FieldValue.arrayUnion(submittedAssignment)

使用这个:

      submittedBy: admin.firestore.FieldValue.arrayUnion(submittedAssignment)

关于node.js - 如何在 Firebase Firestore 中使用 arrayUnion() 将对象推送到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63221195/

相关文章:

ios - 为什么我从数据库中提取信息的函数不起作用?

node.js - JSONAPI实现

node.js - 如何在 Node js Express 服务器中每午夜更新日期变量以从新集合 `data-${date}` 中获取

swift - Childadded 检索一个 key

javascript - 如何从 promise 中的事件处理程序返回值?

node.js - 尝试将 firebase-tools 安装到 Mac Big Sur 时出现 EACCES 错误

javascript - NodeJS Express Api——调用 res.send 外部路由有效,但 res.status 无论如何都不起作用

node.js - 在 Jade 中使 span 位于文本之前

javascript - 是否有 Node 方法来检测网络接口(interface)是否联机?

node.js - Typescript - 如何在 Node.js 上声明全局变量