Reputation: 1827
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
Upvotes: 3
Views: 856
Reputation: 5829
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,
})
Upvotes: 6