Enhancing nested data in Firebase

According to the information from the Firebase note:

When using a single key path such as alanisawesome, the updateChildren() method will only update data at the first child level. Any data passed in beyond the first child level will be treated as a setValue() operation. This is where multi-path behavior comes into play, allowing longer paths like alanisawesome/nickname to be used without overwriting data. This explains the difference between the first and second examples provided.

My goal is to implement a single function called createOrUpdateData(object) in my code. When updating, it correctly updates first-level children, but if a nested object is passed, it ends up deleting all other properties within that nested object.

Below is the code snippet demonstrating this:

function saveUserDetails(email, object){
        var hashedEmail = Utilities.getHashCode(email);
        var userRef = ref.child(hashedEmail);
        return $q(function(resolve, reject){
            userRef.update(object, function(error){
                if(error){
                    reject(error);
                }else{
                    resolve("Updated successfully!");
                }
            });
        });
    }

For example, if I pass the following object:

{
   name: 'Rohan Dalvi', 
   externalLinks: { 
      website: 'mywebsite'
   }
}

It will lead to the deletion of other properties within the externalLinks object. Is there a more efficient and straightforward way to prevent this issue?

In essence, how can I ensure that only nested objects are updated without inadvertently deleting any existing data?

Answer №1

Implementing multi-path updates is a great solution.

let userRef = dbRef.child(hashedEmail);
let updateObject = {
   name: 'Alice Smith', 
   "links/website": 'my-website'
};
userRef.update(updateObject);

Utilizing the "links/website" syntax within the object literal ensures that the nested path is treated as an update rather than a set for the nested object. This method prevents the deletion of nested data.

Answer №2

Here is a more recent solution that works with cloud firestore.

Instead of using "/", you can use "." instead:

var userRef = ref.child(hashedEmail);
var updateObject = {
   name: 'Rohan Dalvi',
   "externalLinks.website": 'mywebsite'
};
userRef.update(updateObject);

Answer №3

If you need to update a nested structure like an object, map, or dictionary in your Firebase database, one approach is to utilize Firestore.Encoder in Swift to convert a Codable class or struct.

Here is an example of how you can achieve this:

Define your models:

import FirebaseFirestore
import FirebaseFirestoreSwift

// UserDetails Model
class UserDetailsModel: Codable {
   let name: String,
   externalLinks: ExternalLinkModel
}    

// ExternalLink Model
class ExternalLinkModel: Codable {
   let website: String
}

When interacting with Firebase:

    import FirebaseFirestore
    import FirebaseFirestoreSwift

    let firestoreEncoder = Firestore.Encoder()

    let fields: [String: Any] = [
        // Using firestore encoder to convert object to Firebase map
        "externalLinks": try! firestoreEncoder.encode(externalLinkModel)
    ]

    db.collection(path)
        .document(userId)
        .updateData(fields, completion: { error in
             ...
    })

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

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Properly relocating the node_modules folder: A step-by-step guide

I decided to relocate my node_modules folder to a different location. To do this, I deleted the original node_modules folder and moved the package.json file to the new desired location. After that, I executed the command npm install to install the node_mod ...

You can activate Lightgallery just one time in VueJs

I am facing an issue where lightgallery can only be opened once. Subsequent clicks on the button are unresponsive. The lightgallery is being used as a component. Within my parent component, I have two buttons for opening image or video gallery ParentComp ...

Tips on how to display a gif image during the loading of ajax content using JavaScript

Currently, I am attempting to load a gif image while waiting for the AJAX data to be loaded and displayed. However, I am struggling with this task. I would appreciate any assistance on how to implement a loading gif in my code for the advanced search feat ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Upon initiating npm start in my React application, an error was encountered: internal/modules/cjs/loader.js:834

Upon downloading my React course project, I proceeded to install dependencies and run npm start. To my dismay, I encountered the following error: PS C:\Users\Marcin & Joanna\Desktop\react-frontend-01-starting-setup> npm start &g ...

Exploring the contrast in importing CSS between the HTML header, JS file, and Vue Component

Exploring the world of Vue with webpack, I find myself curious about the various ways to import CSS. It appears that there are three methods for importing CSS: Adding style sheets directly to HTML headers: <link type="text/css" rel="stylesheet" ... &g ...

Steps to insert additional characters surrounding the innerhtml of an h2 element

After extensive searching, I still can't seem to figure this out. It's possible I'm overlooking something very obvious, and for that, I apologize. My current challenge involves adding two specific characters to multiple h2 elements. While I ...

Filtering rows in JQgrid is made easy after the addition of a new record

Here's the situation I'm facing: Every second, my script adds a new record using the "setInterval" function: $("#grid").jqGrid('addRowData', id, data, 'first').trigger("reloadGrid"); However, when users apply filters while t ...

Expanding the size of a Three.js geometry in one direction

I've been experimenting with scaling geometries on the y-axis, but I've run into an issue where my cube scales both up and down. I found that using mesh.transformY to animate the cube up by half of the scaling value can create the illusion of the ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

React - Implementing toggling of a field within a Component Slot

I find myself in a peculiar situation. I am working on a component that contains a slot. Within this slot, there needs to be an input field for a name. Initially, the input field should be disabled until a web request is made within the component. Upon com ...

Switch between showing and hiding a div by clicking on the panel header and changing the symbol from + to

I need assistance with a panel feature on my website. The panel should expand when the "+" symbol is clicked, displaying the panel body, and the "+" symbol should change to "-" indicating it can be collapsed by clicking it again. There is a slight twist t ...

What is the best way to secure access to Firebase Database for users only from a designated email domain using the latest Firebase cloud functions?

In the past, without the use of cloud functions, it was thought necessary to have an app server in order to securely restrict signups for a Firebase app by email domain. This issue was discussed in this previous question: How do I lock down Firebase Databa ...

I aim to assign a unique identifier to each todo item that is displayed

function handleChange(event) { event.preventDefault() updateItem(event.target.value) } Within this function, my goal is to assign a unique id to each todo element. function addNewTodo(event) { event.preventDefault() setItem({ id: 0 }) ...

Running a JS/JSON function in Snowflake that results in a syntax error

Can anyone help me troubleshoot the issue with the following function? I am receiving this error message: SQL compilation error: syntax error line 1 at position 0 unexpected 'function'. Should I be using JSON Script or Javascript for this? func ...

Tips for preventing HTTP Status 415 when sending an ajax request to the server

I am struggling with an AJAX call that should be returning a JSON document function fetchData() { $.ajax({ url: '/x', type: 'GET', data: "json", success: function (data) { // code is miss ...

RTL in TextInput only functions properly every other time it is rendered

I am facing a strange problem with RTL where everything seems to be flipped correctly except for TextInput, which only works about half of the time. Check out this gif that demonstrates the issue as I switch between English and Hebrew: (click to view a la ...

Obtain text content using JQuery and AJAX rather than retrieving the value

I am struggling with a dynamic table that needs to perform calculations before submitting, requiring the presence of values. However, I want to submit the text from the options instead of the values. Despite trying various approaches, none of them seem to ...