Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function FieldValue.arrayUnion() called with invalid data. FieldValue.serverTimestamp() can only be used with update() and set()

addDeposit(account, deposit) {

    let depositsDoc = this.db.collection("accounts")
                      .doc(account.id)
                      .collection("deposits")
                      .doc("deposits");

    return new Promise((resolve, reject) => {

      deposit.created_at = firebase.firestore.FieldValue.serverTimestamp();

      depositsDoc.update({
        "deposits": firebase.firestore.FieldValue.arrayUnion(deposit)
      })
        .then((a) => {
           resolve('success');
        })
        .catch((error) => {
          reject("failed");
        });

    })
      .then((res) => {
        return res;
      })
      .catch((error) => {
        return error;
      })

    }

**Firestore with angular (Using default firebase SDK not angularfire ) **

I was trying to add timestamp to the deposit object by directly adding a "created_at" property calling the timestamp. By doing this, I am getting the error titled above. How can I add timestamp to a object in an array of objects in firestore?

like image 489
Abdun Nahid Avatar asked Sep 14 '18 03:09

Abdun Nahid


2 Answers

Use this

let deposit.created_at= firebase.firestore.Timestamp.now();

More information can be found at https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#now

like image 68
Pavan Garre Avatar answered Nov 19 '22 20:11

Pavan Garre


You can't use FieldValue.serverTimestamp() as the value to union (add) or remove, to or from, an array type value of a document field. If you want to use that timestamp value, you need to pass it directly to a field you're updating or setting. This is true for everything in the FieldValue class. That class is named this way for a reason - it applies only to field values, not elements of arrays. Note that nested map fields do count as field values. Any involvement of an array in the path is not viable.

You'll have to think of another way you structure your data that meets your needs and also satisfies Firestore requirements.

like image 36
Doug Stevenson Avatar answered Nov 19 '22 20:11

Doug Stevenson