Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database is structured:

https://i.sstatic.net/FE4ZC.png

To accomplish this, I created a loop to search for the userID and change it to null like so:

exports.wipeData = functions.https.onRequest(async (req, res) => {
 const original = 'ppPXA8MvaSRVbmksof0ByOzTxJ92';
    const snapshot = await admin.database().ref('/posts/ivies/userIDs/');
    console.log((snapshot));

    for (let value in snapshot.val) {
      if (value == original) {
      snapshot.val.set("null")
      }
      else {
        console.log(value)
      }
    }

    res.redirect(303, snapshot.ref.toString());

// [END adminSdkPush]
});

Even though this code executes without errors, it fails to replace 'ppPXA8MvaSRVbmksof0ByOzTxJ92' with 'null' as expected. Any assistance would be greatly appreciated. Thanks!

Answer №1

While your overall approach is on the right track, there are a few glitches that need to be addressed.

Consider implementing this revised solution:

exports.clearData = functions.https.onRequest(async (req, res) => {
  const original = 'ppPXA8MvaSRVbmksof0ByOzTxJ92';
  const ref = admin.database().ref('/posts/ivies/userIDs/');
  const query = ref.orderByValue().equalTo(original);

  const results = await query.once('value');
  const updates = {};
  results.forEach((snapshot) => {
    updates[snapshot.key] = null;
  });

  await ref.update(updates);

  res.status(200).send(JSON.stringify(updates));
})

The key modifications include:

  • Your snapshot variable needs to fetch data from the database, which is accomplished by using once('value') in my code snippet.
  • This updated code utilizes a query to target nodes with specific values, making database operations more efficient and cost-effective as your user base expands.
  • The code consolidates all updates into a single object before sending them to the database in a single transaction.
  • The inclusion of await in await ref.update(updates) ensures proper execution only after the database writes have been successfully completed.

Answer №2

I don't have much experience with firebase cloud functions, but in typical client-side firebase code val must be called as a function, and you need to wait for the value from a reference. You might want to attempt something like this:

exports.wipeData = functions.https.onRequest(async (req, res) => {
  const original = 'ppPXA8MvaSRVbmksof0ByOzTxJ92';
  const userIDs = await admin.database().ref('/posts/ivies/userIDs/');
  userIDs.once("value", snapshot => {
    var lookup = snapshot.val();
    for (let key in lookup) {
      var value = lookup[key];
      if (key == value) {
        userIDs.child(key).set(null);
      }
    }
    res.redirect(303, userIDs.ref.toString());
  });
});

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

Safari users encountering invalid dates generated by Moment Js library

Can anyone explain why I am seeing "invalid date" in Safari, but it works fine in other browsers? moment('01/01/2023 11:44:00.000 AM').tz(time_zone, true).format('hh:mm:ss:SS A z') chrome https://i.sstatic.net/PeFBp.png safari https ...

Unable to run the method in the parent component from the child component

I am attempting to trigger a method to run on a parent component when a button within one of its child components is clicked. I am utilizing single file components with Webpack. Below is the code for the child component: <template> <button v-on ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. Referring to the image provided, the first 'Product & Total Product' element ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

Filter arrays in Vue.js using checkboxes

I'm currently working with vuejs and I need to implement a filtering feature for my array using checkboxes. I attempted to use v-model to filter the array based on three specific options: "Truck," "Van," or "Tx". However, I haven't been successfu ...

Unraveling the mystery: Retrieving event.target.value in a React component

Having trouble accessing the event.target.value from a React child Component, but not an HTML tag? In this scenario: the Button tag (React Component) cannot access event.target.value, while the button tag (HTML tag) can. import React from "react"; impor ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Using the same ID to both assign and retrieve a value

Currently, I'm utilizing the x-editable library for jQuery, which is an in-place editor. Below is a snippet of my working code: <?php $num_rows = 1; // Fetching records from the "tblstudent" table and storing them in $row while ($row = ...

When working with jQuery, I encountered the error message "is not a function" because I mistakenly tried to use a function more than

While working on a pager, I encountered an issue with a function that is initially invoked when the document loads. However, when attempting to use it a second time, an error "is not a function" occurs. I am curious about the reason behind this phenomenon. ...

Meteor: Incorporating New Fields when Creating an Account

Currently, I am experimenting with the Meteor Roles package found at https://github.com/alanning/meteor-roles in order to add a new field to the user model. The user creation process goes smoothly without any issues, however, the 'roles' field t ...

Utilizing JSON format for processing HTTP requests in JavaScript with Node.js

I'm working with a snippet that retrieves data in JSON format, but I'm interested in manipulating the data instead of just outputting it to the console. var request = require('request'); var headers = { 'Connection': ' ...

Can data be transferred within a callback to the function it encapsulates?

I am currently working on developing a user login system and I find myself in need of querying the database. Being a beginner in coding, I am grappling with the concept of callbacks and how data can be passed once the callback has been executed. My dilemm ...

Determine whether the object is facing the specified position

I'm attempting to verify whether an object (this.target) is facing towards a particular position (newPosition). Here's what I currently have: new THREE.Matrix4().lookAt( newPosition, this.target.position, this.target.up ) == this.target.matrix ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...