In TypeScript, when utilizing CloudFunction, one way to pass admin.firestore.FieldValue.serverTimestamp() to the update() method is by including it as

Is it possible to include admin.firestore.FieldValue.serverTimestamp() in an array when using the update() method? I'm trying to achieve something like this:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp(functions.config().firebase);
exports.sendNote = functions.https.onCall(async(data,context)=>{
const numeroSender: string = data['numeroSender'];
const amisA = admin.firestore().collection('Amis').doc(numeroReceiver);
const connaissanceABBA:number = 3.0;
const version:number = 1;
const time = admin.firestore.FieldValue.serverTimestamp();
await amisA.update({
            [`amis.${numeroSender}`] : [time,connaissanceABBA,version]
        });
});

However, I am encountering the following 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 value. FieldValue.serverTimestamp() cannot be used inside of an array (found in field `amis.+33651177261`.`0`).
at WriteBatch.update (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/write-batch.js:367:23)
at DocumentReference.update (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/reference.js:372:14)
at Object.<anonymous> (/user_code/lib/index.js:121:25)
at next (native)
at fulfilled (/user_code/lib/index.js:4:58)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Answer №1

To replace admin.firestore.FieldValue.serverTimestamp(), consider using admin.firestore.Timestamp.now()

const currentTime = admin.firestore.Timestamp.now();
await amisA.update({
        [`amis.${senderNumber}`] : 
           {
    knowledgeABBA: knowledgeABBA,
    version: version,
    ts: firebase.firestore.FieldValue.serverTimestamp()
  }
});
});

Answer №2

The error message clearly states that "FieldValue.serverTimestamp() cannot be used inside of an array".

This is evident in the following code snippet:

const time = admin.firestore.FieldValue.serverTimestamp();
await amisA.update({
            [`amis.${numeroSender}`] : [time, connaissanceABBA, version]
        });
});

To resolve this issue, consider altering your data model and using a map instead of an array. Here's an example of how to do it:

const time = admin.firestore.FieldValue.serverTimestamp();
await amisA.update({
            [`amis.${numeroSender}`] : 
               {
        connaissanceABBA: connaissanceABBA,
        version: version,
        ts: firebase.firestore.FieldValue.serverTimestamp()
      }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

ERROR: Unhandled promise rejection: Route cannot be found. URL Segment: 'details'

My current setup involves a router configuration in my Angular application. Below is the code snippet showcasing my router settings: import { Route, RouterModule } from '@angular/router'; import { ProjectDetailsComponent } from '../componen ...

unable to successfully complete parameter in angular 2

After receiving data from the API, I am using the subscribe method to execute lines of code. Below is the code snippet: this.attRecService.getAgendaData(moment(this.viewDate).format('YYYY-MM')).subscribe( resp => { this.ag ...

JavaScript/TypeScript - Restricting to only assigned properties in an object

Consider this scenario: Suppose we have an object with the following properties: const objOne = { car: 'ford', location: 'Munich', driver: 'John' } and a second object that only contains some of the properties from th ...

Download pictures from swift into typescript with the help of share extensions

Currently, I am working on setting up Share Extensions in my ionic3 application. To begin with, I followed these steps: Firstly, I built the app and then launched it in Xcode. After that, I added a Share Extension by navigating to File -> New -> Ta ...

Experiencing a platform browser error since updating to Ionic 5 from Ionic 4

ERROR: Uh-oh! Looks like there's an issue in the node_modules directory. The error message reads: ERROR in node_modules/@angular/platform-browser-dynamic/platform-browser-dynamic.d.ts(15,10): error TS2305: Module '"node_modules/@angular/compiler ...

Optimal methods for setting state in function components within React

As I delved into function components in React, I stumbled upon 2 methods for defining state. However, discerning the disparity between the two proved to be quite puzzling. The initial approach is showcased below: export function TestComponent() { const [ ...

Displaying information sourced from an API

const [error, setError] = useState(null); const [isLoaded, setIsLoaded] = useState(false); const [items, setItems] = useState([]); useEffect(() => { fetch("api-url") .then(res => res.json()) .then( (result) =&g ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Serialization of objects is not possible in Angular JS post requests

At the moment, I am utilizing an AngularJS Post method to send data to my controller instead of a traditional form submission. The issue I am encountering is that after the post call, the object named sharingInfo in the controller always gets set to null. ...

Developing a NextJS application within an existing Firebase project

Currently, I am looking to leverage NextJS on Firebase for hosting my website. While the online resources available have guided me through setting up a NextJS app and initializing a Firebase project, my situation is slightly different. I already have exi ...

Show the attribute of an element in a pop-up window

I have a modal from ngx-bootstrap that I want to display in there a property of my object let's say the name: public students = [ { id: 1, name: 'lorem'} In this button that is common for all entries in the table (each row has this butt ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

Streamline the TypeScript interface for retrieved data from an API

I am looking to retrieve movie data from the omdbapi. Currently, I am experimenting with incorporating typescript to precisely define the data fetched from the endpoint (I am still learning typescript). When examining the structure of the retrieved data, ...

"TypeScript harnesses the power of inference to determine the type of

Anticipated result would be number | never[]. However, it is actually number | never[] | undefined. type T1 = (number | undefined)[]; const myFunc = (arr: T1, index: number): any => { const result = arr[index] === undefined ? [] : arr[index]; r ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

Can you explain the significance of the angle-bracket notation in Typescript?

Typescript confuses me with this syntax: myFunc<MyType>(myObject) Can someone clarify what this means? I know that <MyType>myObject is a type-assertion, but when it's placed between the function name and the open parenthesis, I'm lo ...

When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model. The recording is saved as an mp4 file, which I ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...