The update operation for the Reference object encountered an error: The first argument includes a function within a

I'm encountering errors while attempting to create a simple cloud function that detects likes on the RD and then adds posts to a user's timeline.

How can I resolve this issue? What mistake am I making?


(The 2 errors below are from the Firebase Cloud Functions console)

onPostLike

Error fetching likers username: Error: Reference.update failed: First argument contains a function in property 'UserFYP.Bke7CYXP31dpyKdBGsiMOEov2q43.0PMdzaOyYBejf1Gh6Pk1RRA5WNJ2.postID.node_.children_.comparator_' with contents = function NAME_COMPARATOR(left, right) {

onPostLike

TypeError: Cannot read property 'get' of undefined at ServerResponse.json (/workspace/node_modules/express/lib/response.js:257:20) at ServerResponse.send (/workspace/node_modules/express/lib/response.js:158:21) at likerUIDRef.once.then.catch.error (/workspace/lib/index.js:669:52) at process._tickCallback (internal/process/next_tick.js:68:7)

Related TypeScript:

 function addPersonalizedFYPPosts(whoLikes: string, postUID: string, postID: string) {
      
      //need to use data to fetch my latest likes
      //then I use the likers data to add the new post to his fypTimeline

      const ref = admin.database().ref(`Likes/${postUID}/${postID}/media1`);
      return ref.once("value") 
      .then(snapshot => {

        //use snapshot to get the my latest like ??
        //Now with this ssnapshot we see other people who liked the same post this liker has. get one of their UIDs and see what else they liked add that to thte likers timeline. 

        var i2 = 0

        snapshot.forEach((theChild) => {

          if (i2 == 0) {

            let uid = theChild.key
          
            //do what you want with the uid
  
            //const userWhoAlsoLiked = snapshot.forEach
  
            const likerUIDRef = admin.database().ref(`YourLikes/${uid}`);
            likerUIDRef.once("value")
            .then(snap =>{
              //const username = snap.val()
              
              var i = 0
              snap.forEach((child) => {
                //UserFYP
                if (i == 0) {
                  let timelineID = child.key;
                  let timeStamp = child.child("timeStamp");
                  let newPostID = child.child("postID");
                  let postUid = child.child("uid");
    
                  //admin.database().ref(`UserFYP/${whoLikes}/${timelineID}/`).update(["":""])
                  admin.database().ref(`UserFYP/${whoLikes}/${timelineID}/`).set({"postID": newPostID, "uid": postUid, "timeStamp": timeStamp})
                  .then(slap =>{
                    console.log("Success updating user FYP: " )
                    return Promise.resolve();
                  })
                  .catch(error => {
                    console.log("Error fetching likers username: " + error)
                    response.status(500).send(error);
                  })
                  i++;
                }
                // return;
              })
              
            })
            .catch(error => {
              console.log("Error fetching likers username: " + error)
              response.status(500).send(error)
            })
            
            return;
            
            i2++;
          }
      })

      })
      .catch(error => {
        console.log("The read failed: " + error)
        response.status(500).send(error)
      })  

    }

export const onPostLike = functions.database
.ref('/Likes/{myUID}/{postID}/media1/{likerUID}')
.onCreate((snapshot, context) => {
  const uid = context.params.likerUID
  const postID = context.params.postID
  const myUID = context.params.myUID
  //addNewFollowToNotif(uid, followerUID)

  return addPersonalizedFYPPosts(uid,myUID,postID);
})

Answer №1

When you use the child() method on a DataSnapshot, it returns another DataSnapshot. For example:

  snap.forEach((child) => {
    //UserFYP
    if (i == 0) {
      let timelineID = child.key;
      let timeStamp = child.child("timeStamp");
      let newPostID = child.child("postID");
      let postUid = child.child("uid");

In this code snippet, your local variables are snapshots which contain functions for accessing them. However, since you can only write JSON to the database, the snapshots are being rejected.

To resolve this issue, you should modify the code as follows:

  snap.forEach((child) => {
    //UserFYP
    if (i == 0) {
      let timelineID = child.key;
      let timeStamp = child.child("timeStamp").val();
      let newPostID = child.child("postID").val();
      let postUid = child.child("uid").val();

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

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Node path response not being properly configured

Just diving into the world of node and typescript and could use a bit of guidance. Currently utilizing node/express/postres as backend and leveraging https://github.com/typeorm/typeorm as an orm, which offers a function to open a connection structured as f ...

Learn the process of invoking Firebase Functions through AngularFire

My project involves creating a Firebase Cloud function using functions.https.onRequest to act as an API that returns JSON data from the Firebase Realtime database. After some research, I discovered functions.https.onCall, which provides authentication fun ...

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

Despite encountering the 'property x does not exist on type y' error for Mongoose, it continues to function properly

When working with Mongoose, I encountered the error TS2339: Property 'highTemp' does not exist on type 'Location' when using dot notation (model.attribute). Interestingly, the code still functions as intended. I found a solution in the ...

What is the best way to send my Array containing Objects to the reducer using dispatch in redux?

I'm currently facing an issue where I can only pass one array item at a time through my dispatch, but I need to pass the entire array of objects. Despite having everything set up with a single array item and being able to map and display the data in t ...

Can images taken with a camera be uploaded directly to Firebase Storage?

Currently working on a React.js project to develop an application that can capture photos and upload them to Firebase Storage. Utilizing the react-webcam library to take a photo with this command: const ImgSrc = webcamRef.current.getScreenshot(); Attempte ...

Issue with music in Phaser3 game not playing correctly when transitioning to a new scene

I'm completely new to Phaser and I've encountered an issue with adding a start menu to my main platformer scene. The gameplay scene plays music seamlessly, but when I introduce a start menu, things start to go wrong. Here's a snippet of the ...

Guide on integrating the plyr npm module for creating a video player in Angular2

Looking to implement the Plyr npm package in an Angular 6 application to create a versatile video player capable of streaming m3u8 and Youtube videos. The demos on their npm page are written in plain JavaScript, so I need guidance on how to integrate it in ...

Proper method for determining return type through the use of `infer`

I need to find out the return type based on input values, like in the code below: type ReturnType<S> = { array: S extends 'number' ? number[] : S extends 'string' ? string[] : never; value: S extends 'number' ? n ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

The Firebase database reference function is not recognized in Node.js

Could someone help me identify the issue in my code before I revert back to MongoDB? The project is built with Node.js (Next.js) This is how I've configured Firebase (works for Google Login authentication): import { initializeApp } from 'fireba ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Using Angular 4 Component to Invoke JavaScript/jQuery Code From an External File

I have written a jQuery code that is executed at ngAfterViewInit(). //myComponent.ts ngAfterViewInit() { $(function () { $('#myElement').click(function (e) { //the code works fine here }); } However, I want t ...

Troubleshooting issues with connecting Flutter on Android using the USB port

I am using a Windows operating system and want to test my Android app directly on an android device via USB. My smartphone is running on Android 5.1 Lollipop. However, I keep encountering the following error: Unhandled Exception: [core/not-initialized] Fi ...

TypeORM find query is returning a data type that does not match the defined entity type

In my infrastructure module, I am using the code snippet below: import { Student } from "core" import { Repository } from "./Repository" import { Database } from "../../db" export class UserRepository<Student> extends Re ...

The absence of index.html in the dist/browser folder is a common issue encountered when building Angular Universal projects with the command "npm run build:ssr"

Following the installation of Angular universal by executing: ng add @nguniversal/express-engine I proceeded to build the project using: npm run build:ssr However, when attempting to serve the project with: npm run serve:ssr An error message appeared: E ...

Attention: WARNING regarding the NEXTAUTH_URL in the Development Console

While working on my Next.js web application with next-auth for authentication, I came across a warning message in the development console. The message is related to reloading the environment from the .env.local file and compiling certain modules within the ...

Tips for creating a type-safe union typed save method

My goal is to build a versatile http service that includes a method like save(value), which in turn triggers either create(value) or update(value). What sets this requirement apart is the optional configuration feature where the type of value accepted by c ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...