Pushing multiple objects in Firebase at the same time

Let's assume that we have the following skeleton in Firebase:

terminal
"analytics": {

}

We want to add:

  1. User's first access timestamp
  2. User's first access url
jsx
let userTimeStamp = {
    timeStamp: (new Date()).getTime()
};

let userUrl = {
    url: window.location.pathname
};

The goal is to have the following database structure:

terminal
"analytics": {
    "users": {
        "-M5hdLMC_7vjmGxDhDWI": {
            "timeStamp": 1587756229114,
            "pageViews": {
                "-M5hdLMDmBVtzogHKj10": {
                    "url": "/"
                }
            }
        }
    }
}

As you can see, there are two keys involved and we need to push them at the same time. To achieve the goal:

jsx
// Getting the keys
let firstKey  = firebase.database().ref('analytics/users').push().key;
let secondKey = firebase.database().ref(`analytics/users/${firstKey}/pageViews`).push().key;

// Declaring the object to update
let objectToUpdate = {};

// Defining properties of the object
objectToUpdate.users = {};
objectToUpdate.users[firstKey] = userTimeStamp;
objectToUpdate.users[firstKey].pageViews = {}; 
objectToUpdate.users[firstKey].pageViews[secondKey] = userUrl;

// Updating 
firebase.database().ref('analytics').update(objectToUpdate);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.