Nakshatra Saxena
Nakshatra Saxena

Reputation: 33

How to push an object in an array with arrayUnion() in Firebase Firestore?

My current document looks like this:

{
    "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"
}

I want to push an object in the 'submittedBy' field but I get an error. The code I'm using right now is:

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` });
    });

But I'm getting this error

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).

Upvotes: 3

Views: 1122

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

You're mixing up Firestore SDKs. If you use the Admin SDK to make the update, you will also need to use the Admin SDK to specify FieldValue type values.

Instead of this:

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

Use this:

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

Upvotes: 8

Related Questions