Timestamps Update in Cloud Functions Triggered by Warnings

My Firebase Cloud Functions setup looks like this:

index.js

const functions = require('firebase-functions');
const trackVote = require('./trackVote')
const admin = require('firebase-admin');
admin.initializeApp();

exports.trackVote = trackVote.handler;

trackvote.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.handler = functions.firestore.document('/Polls/{pollId}/responses/{userId}').onCreate((data, context) => {
                  const answerSelected = data.data().answer;

                  const answerRef = admin.firestore().doc(`Polls/${context.params.pollId}/answers/${answerSelected}`);
                  const voteCountRef = admin.firestore().doc(`Polls/${context.params.pollId}`);

                   return admin.firestore().runTransaction(t => {
                               return t.get(answerRef)
                                   .then(doc => {
                                       if (doc.data()) {
                                           t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
                                       }
                                   })
                           }).then(result => {
                               return admin.firestore().runTransaction(t => {
                                           return t.get(voteCountRef)
                                               .then(doc => {
                                                   if (doc.data()) {
                                                       t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
                                                   }
                                               });
                                        });
                           });
           });

A warning I encountered is as follows. I am looking to make changes in my code for both cloud functions and client-side. Specifically, how the update would impact index.js and trackVote.js files:

TypeError: db.settings is not a function
at Object.<anonymous> (/Users/troychuinard/Code/FanPolls/functions/index.js:13:4)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:21:11
at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:61:3)

Answer №1

const firebaseAdmin = require('firebase-admin');
const firebaseFunctions = require('firebase-functions');
let firebaseAppInstance;
if (firebaseAdmin.apps.length > 0) {
  firebaseAppInstance = firebaseAdmin.app()
} else {
  firebaseAppInstance = firebaseAdmin.initializeApp(firebaseFunctions.config().firebase)
}

let firestoreDb = firebaseAppInstance.firestore()
firestoreDb.settings({ timestampsInSnapshots: true })

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

Making an HTTP redirect request in a NodeJS environment

I am in the process of developing a basic NodeJs Server. Whenever this server receives a request, it performs certain actions in the background and then redirects the user to another webpage. This is the code snippet I am working with: const http = require ...

Allow npm to refresh the node_modules/.bin symbolic links

In the event that the top level node_modules/.bin directory has been deleted, is there a method to instruct npm to recreate the symlinks without having to delete the entire node_modules directory and perform a complete npm install again? ...

Is it possible to transmit information using the express next() function?

I am currently developing a web application that involves authentication process and session management using express. I have successfully implemented the backend sessions functionality. Now, my goal is to display on the user interface the information of t ...

When utilizing fs.readdir along with fs.statSync, you may encounter the error message "ENOENT: no such file or directory

This code snippet is functional: var promise = new Future(), dirs = [], stat; Fs.readdir(Root + p, function(error, files){ _.each(files, function(file) { //stat = Fs.statSync(file); //if ( s ...

Transmitting data from a server to a client in NodeJS

Help needed with emitting data from server to client. I keep getting undefined on console.log for the res variable in my client-side JavaScript code. Here is my server-side code: const express = require('express') const app = express() const se ...

Set up your server on Vercel platform for seamless deployment

Currently, I am following a tutorial by CJ, where he demonstrates deploying his server using now. However, the tutorial is now outdated as now has been replaced with vercel. I am unsure about how to proceed with vercel. Can someone provide guidance on thi ...

Why is the helpers folder so important in an Express application?

Exploring the ideal hybrid folder structure to meet our needs is my current project. After sifting through numerous resources and sources, I stumbled upon a folder labeled helpers housing files with a .js extension. |-- app | |-- controllers | | `- ...

Local Environment Variables for Azure Functions JavaScript Development

When working with Azure Functions in JavaScript locally, how can you manage Node environment variables for use when running functions locally with azure-functions-core-tools using the command func host start --debug? The documentation for Azure Functions ...

In node.js, the global variable scope is returning an [Object object] rather than a string

In my request function, I successfully receive the tokenName in the response. However, I am struggling to access it globally so that I can save it in the database. request(options,function (error, response, body) { tokenName = body.notification_key ...

Following the npm update, encountering errors with webpack

Upgrading the npm package to version 8.2.0 has caused issues in my React application. Here is a screenshot of the problem: https://i.stack.imgur.com/noQIz.png These are the error messages I see in the console: [HMR] Waiting for update signal from WDS.. ...

Leveraging the combined output from find command in uglify-js and sass

I have been experimenting with using NPM as a build tool and encountered an issue that has me puzzled. My goal is to use find to retrieve a list of files and then pass them into a command like uglify-js or sass: find ./views -type f -name '*.js' ...

Headers cannot be set once they have already been sent in an express js application

After reviewing various responses to this query, I am baffled as to why this error keeps appearing despite having res.send() in multiple paths. In my code (expressjs 4.13), it looks something like this: var user ={ username: "some", password: "a" ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Node Express app intercepts a POST request, increments a counter, and triggers an error after a certain threshold

In my project involving Node Express/Angular Civic, I am faced with the challenge of integrating it with a 3rd party API where each call incurs a cost of $1.00. While I am willing to cover some of the expenses, I want to implement a mechanism to halt the P ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

How can I troubleshoot and resolve this npm error that's causing issues for my project?

$npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /home/gatua/package.json npm ERR! errno -2 npm ERR! enoent ENOENT: no such file or directory, open '/home/gatua/package.json' npm ERR! enoent This error is due to npm not ...

Images stored in Firebase Storage are not appearing on my Next.js application

I've been using the Next.js template from Vercel and attempting to switch out the logo image at the bottom with one stored in Firebase storage. Although I have configured the next.config.js file without any errors, the image does not appear on the pag ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

Why is middleware being triggered even if the specified mount path is not its own?

As a beginner in the world of node and express, I am delving into exploration. Recently, I created two middleware functions each with its own mount path. Surprisingly, MIDDLEWARE 2 is being invoked even when the incoming request is not intended for it. ...