3

I want to insert an object to the Firestore document as per the code mentioned below. but it's throwing the error

   .update({
           "comments": firebase.fieldValue.arrayUnion({
            userId,
            comment: data.comment,
            createdAt: firebase.fieldValue.serverTimestamp(),
     })

Error:

FirebaseError: Function FieldValue.arrayUnion() called with invalid data. FieldValue.serverTimestamp() can only be used with update() and set() (found in document...)

How can I add a timestamp to the pushed array object or is there any other way to achieve a similar result? what am I getting from the error above is I can't use the timestamp inside arrayUnion

0

1 Answer 1

6

You can't use FieldValue.serverTimestamp() as the value to an arrayUnion since that function does not return a timestamp but a sentinel to be used in a set() or update(). In order to do that you need to get the actual timestamp class value. And the way to get this value differs from the local to the admin SDK, so depending on what you are using you could do something like this:

For the Admin SDK:

import admin = require('firebase-admin');

const created_at = admin.firestore.Timestamp.now()

For the Local SDK:

import { Timestamp } from '@google-cloud/firestore';

const created_at = Timestamp.now()

And then you can update your document by doing this:

.update({
       "comments": firebase.fieldValue.arrayUnion({
        userId,
        comment: data.comment,
        createdAt: created_at,
 })
Sign up to request clarification or add additional context in comments.

4 Comments

It's not working, I think this serverTimestamp can only be called from inside of set or update methods
Yeah, I am updating the answer, give me a sec.
Edited, try it out. :)
Important note: FieldValue.serverTimestamp() encodes a token into the document field that gets translated into a timestamp using the clock on Google's servers whenever the write operation is received. But Timestamp.now() generates the timestamp using the client machine's clock, which could be wrong, even drastically wrong. Read more about this here. So I would love to hear another way of using FieldValue.serverTimestamp() with arrayUnion. If anyone knows please share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.