Implementing setDoc with Firebase-Admin using Typescript in Firestore

I'm having issues with my code in config/firebase.ts:

import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'

const firebaseAdminApp = initializeApp({
    credential: cert({
        privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
        clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
        projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
    }),
    databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});


const firestore = getFirestore(firebaseAdminApp);

export default firestore

When I attempt to upsert data, the following code is used:

import firestore from "../config/firebaseAdmin";

const upsertInstance = async (instance: Instance) => {
  const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
  const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
  return res
}

However, upon execution, I encounter this error message:

Error: expected a function

What could be causing this issue?

Answer №1

The Firebase Admin SDK is not fully modular at this point, unlike the client SDK, so you will need to use namespaced syntax. The Firestore instance from the Admin SDK may not integrate perfectly with client SDK functions. Consider refactoring your code as demonstrated below:

export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"

const updateInstance = async (instance: Instance) => {
  const response = await db.doc(`instances/${instance.uri}`).set(instance);
  return response;
}

For more details, refer to the official documentation.

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

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

converting the names of files in a specific directory to a JavaScript array

Currently working on a local HTML document and trying to navigate through a folder, gathering all the file names and storing them in a JavaScript array Let's say I have a folder named Videos with files like: - VideoA.mp4 - VideoB.mp4 How can I cre ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

Ways to position divs without causing them to collapse or override existing divs

I am currently developing a demonstration in which users can select jQuery areas to create square blocks. When a user selects an area and adds a comment with color, the entire block is displayed at a specific position. This feature is working perfectly as ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

I encountered a problem in Javascript where I was unable to get the video.getCurrentTime() function to display the current time of

While everything else in my code is running smoothly with setInterval, there seems to be an issue with video.getCurrentTime() not displaying in the div id = "test" when the video is playing. I've been trying to figure out why this is happening. Here&a ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Three.js tutorial: Rotating items on each axis individually

Looking to create an interactive 3D item that users can rotate with their mouse freely? I experimented with using three quaternions, one for each axis, and then multiplying them together to determine the final position of the item. // Initializing xQuat, y ...

Creating visually appealing tables in React.js

Having trouble with table rendering in React. The buttons in the table cell are not styled properly and do not center within their div. Additionally, the table border is cut off where there are buttons or empty headers. Need help figuring out what's g ...

Having difficulty accessing the API response accurately

The response from my API is as follows: {"__v":0,"short":"8xdn4a5k","_id":"5404db5ac27408f20440babd","branches":[{"version":1,"code":""}],"ext":"js","language":"javascript"} When I use this code, it works perfectly: console.log(response.short); However ...

What is the best way to assign SnapshotChanges to an Observable Firebase variable?

I'm facing an issue where I can't access the id of a document even though it's visible when printing the object this.ressobj. However, when I try to use ressobj.id_doc in the card, the id of the document is not visible. this.ResColeccion ...

Exceeded Limit: Google Maps API cannot process more than 10 destinations at this time

After spending the entire day researching, I am still unable to find a solution that solves my issue. I am utilizing the Google Maps Distance Matrix Service with 1 origin and 14 destinations. While testing the modified sample code from Google (https://deve ...

Attempting to create a pathway for removing a profile and user from mongoDB

Hello, StackOverflow community! This is my initial post here and I'm excited to seek guidance. I recently created a delete route in Express to delete both a user and their profile: // @route DELETE api/profile/ // @desc Delete user and profile / ...

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

What is the best way to implement multiple ternary operators within HTML code?

Consider the following code snippet: It currently applies CSS classes up to red4, but I want to apply CSS classes up to red11. Additionally, the variable "size" in myData should be dynamic. For example, size could range from 0-20 // 0-100 // 0-10000, etc., ...

The RxJS observable fails to initiate the subscribe function following the mergeMap operation

I am attempting to organize my dataset in my Angular application using the RxJS operators and split it into multiple streams. However, I am facing difficulties making this work properly. Inside my SignalRService, I have set up a SignalR trigger in the cons ...

When trying to set up Plaiceholder in a Next.js/Webpack 5 environment, you may encounter the following issue: "Error: Module not found - Can't resolve 'child_process

While working on my Next.js application, I encountered an issue after installing/importing Plaiceholder for generating placeholder images. The error message I received is: Module not found: Can't resolve 'child_process' Node version: 14.18. ...

Controller experiencing issues with Ajax passing null value

My webpage features a dropdown menu with a list of ID's to choose from. When a customer selects an option, it should update the price total displayed on the page. To achieve this functionality, I'm working on implementing an AJAX call that will u ...

What is the best method to position images in the same way as seen in the screenshot

Any tips on aligning images shown in the screenshot? Please note that the images will be from the backend. https://i.stack.imgur.com/LnYLM.jpg I experimented with code to position images using top, right, left, and bottom properties, but it becomes cumb ...