Firebase: Saving data to a nonexistent object

I am currently facing a challenge in saving the result of a serviceId to a services object within a parent entity named provider1, especially since the services object has not been initialized yet.

The structure of my Firebase data is as follows:

"providers" : {
  "provider1" : {
    "name" : "The Whittington Hospital",
  }
}

This is my current approach to save the serviceId:

for (var providerKey in service.providers) {                       
  var providerId = providers.$getRecord(providerKey);             
  providerId.services[serviceId] = true;                          
  providers.$save(providerId);                                     
}

Unfortunately, I encounter an issue when setting the value of [serviceId] to true because the services object has not yet been created and is undefined.

Since Firebase does not allow the creation of empty objects, I cannot simply add an empty services: {} object under provider1.

If anyone has suggestions on how to address this issue, I would greatly appreciate it. Thank you for your assistance!

Answer №1

If the object does not exist, you can simply create it by following this code:

for (var key in data.services) {                       
    var provider = services.$getRecord(key);    
    if(!provider.info){
        provider.info = {};
    }
    provider.info[dataId] = true;                          
    services.$save(provider);                                     
}

Check out this Plunker for a visual demonstration: http://plnkr.co/edit/5Nvc9x1F3dT0WGNrCykK?p=preview

This example is based on a tutorial, so try adding a message first and then click the button to connect the service to the last message.

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

When onSucess is called within a Vue view, the metadata parameter returns undefined, whereas it works properly inside a

In my Vue component for Plaid Link, there is a function/action in my Vuex store called onSuccess. This function is supposed to call my backend API to exchange the public token for an access token and send some data about the link to the backend. However, I ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

The Shell Application is not refreshing React HtmlElement Micro Front end

I am currently facing an issue when trying to inject the following React MFE into another Angular shell application. The MFE loads successfully the first time, but if it is hidden or removed from the DOM and then reloaded, it fails to load. Could you plea ...

Can we tap into the algorithm of curveMonotoneX in d3-shape?

I'm currently using curveMonotoneX to draw a line in d3 import React from 'react'; import { line, curveMonotoneX } from 'd3-shape'; export default function GradientLine(props) { const { points } = props; const lineGenerator ...

An issue with the image filter function in JavaScript

I am currently working on a simple application that applies image filters to images. Below is the code I have written for this purpose. class ImageUtil { static getCanvas(width, height) { var canvas = document.querySelector("canvas"); canvas.widt ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

Why is it not possible to pass references when utilizing a self-invoking function?

I have been experimenting with the IIFE pattern for some of my modules lately and encountered a problem that has stumped me. In my current project, I need to pass a few global variables for usage. One of these is the global googletag variable which initial ...

Troubleshooting problem with transmitting data using the b4j jQuery WebSocket library

I'm seeking guidance on the process of sending data through a custom library that connects to a Java server operating as a WebSocket server. The code I'm using for successful connection is: <script src="https://ajax.googleapis.com/ajax/libs/ ...

Using JavaScript and PHP to dynamically update a field based on two input values within a row of a table

Currently in the process of developing a dynamic profit margin calculator for a personal project. Overview Data is retrieved from a database table using SQL and PHP After necessary validations, the data is dynamically displayed as rows in an HTML table ...

Avoid running another process before the current one finishes in jQuery

I have a situation where I am using $.ajax inside a for loop in jQuery. for(var i=0; i < 2; i++) { $.ajax({ url :"/models/getdata"+i, dataType:"json", success:function(data) { } }); } The issue is that before the success function for i=0 completes, ...

The proper method for defining a model in AngularJS?

I need help defining a model in my application. I currently have my ng-model set to model.test and it appears to be functioning correctly when I use alert($scope.model.test); Do I always have to reference it as $scope? When should I initiali ...

Ways to rejuvenate an Angular element

Last month, I was called in to rescue a website that was in chaos. After sorting out the major issues, I am now left with fixing some additional features. One of these tasks involves troubleshooting an angular code related to videos and quizzes on certain ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Utilize AngularJS to present JSON data generated from PHP in a tabular format

After retrieving data from a MySQL database, I am formatting it into JSON. The fetch.php file: https://i.stack.imgur.com/4UbOs.png When I use echo $json;, the following is output to the console. [{"id":"1","emp_no":"1111","first_name":"1fname","last_n ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

Implementing Jquery Datatables in C# Codebase

I'm struggling to populate my jQuery Datatable with a List. Currently, I am writing the list to a file and accessing it in my view-model. Is this the correct approach? This is the snippet of my code: List<string> list = new List<string> ...

Unlock the powers of Express, Passport, and Redis sessions!

Lately, I have been utilizing the default MemoryStore for my Express sessions and everything has been running smoothly. However, I encountered a setback where all session data was lost between restarts. To address this issue, I am now attempting to configu ...