Update and push at the same time in Firebase

Let's assume that you have the following structure in Firebase:

json
{
    'name': 'Erik',
    'lastPost': '27-10-2020',
    'posts': {
        '-MMFpPpFFi3CjLARb59_': 'Hi'
    }
}

If you write a new post, lastPost needs to be updated to the current date and you need to push a new post on the posts branch.

Both actions should be done at the same time. That means you need to update some properties of the tree without deleting the current children.

In Firebase, you can use the update() function to achieve that. You'll need to pass an object as an argument, where each object property corresponds to the path that you want to update.

Example:

javascript
// Generating new message
let newPost = 'Bye';
let current = '16-11-2020';

// Creating the new key
let key = firebase.database().ref().push().key;

// Defining the object to update
// Notice how variable paths are defined between brackets []
// Brackets are used as dynamic property keys
let object = {
    
    lastPost: current,
    [`posts/${key}`]: newPost
    
}

// Calling update method
firebase.database().ref().update(object);

At this point, you'll have the following structure in Firebase:

json
{
    'name': 'Erik',
    'lastPost': '16-11-2020',
    'posts': {
        '-MMFpPpFFi3CjLARb59_': 'Hi',
        '-MMFpYvu-4RnfEA00mWY': 'Bye'
    }
}

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