vijay053
vijay053

Reputation: 872

How to add a new field in Array of data in Firebase realtime database using Firebase Functions?

I am new to firebase. I have data in Firebase realtime database with following structure. My requirement is to add a new field to multiple (selected) records present under “user”.

Initial Data

db—>user
    —pushId_1 (Auto Generated via push command)
        name: user1
    pushId_2
        name: user2

Required final Data with one more field added (“newField”)

db—>user
    —pushId_1
        name: user1
        newField: sample data
    pushId_2
        name: user2
        newField: sample data

I have written following code to do this.

exports.sampleFunction = functions.database.ref('/db/user/{pushId}/')
    .onCreate((snap, context) => {
        console.log('onCreate called with snapshot id = ' + snap.key);
        admin.database().ref('/db/user/').once('value').then(snapshot => {
            if (snapshot.numChildren() > 1) {
                var updates = {};
                var count = 0;
                snapshot.forEach((child) => {
                    if (!child.hasChild('newField') && count < 2) {
                        updates[child.key] = { newField: 'sample data' };
                        count++;
                    }
                });
                //return snapshot.ref.set(updates);   //set is also giving same result.
                return snapshot.ref.update(updates);
            }
            return null;
        }).catch(error => {
            console.error("error in fetching data from db." + error);
        });
        return null;
    });

Problem is, this code is deleting existing field "name" and replacing it with “newField”. Can you please help me in appending this new field to data without deleting existing fields.

Thanks

Upvotes: 1

Views: 3607

Answers (1)

Umar Hussain
Umar Hussain

Reputation: 3527

That's because you are using set instead of updating the node.

Set replaces any content while update adds fields if missing and only replace fields if they are present in new data.

return snapshot.ref.update(updates);

Also you are setting the data wrong to update. In key you need to have path relative to the ref you are calling the update instead of nested objects. Instead of updates[child.key] = { newField: 'sample data' };, it should be

updates[`${child.key}/newField`] = 'sample data';

now when you call update with the child parent i.e. snapshot, it knows exactly which fields to update.

See the docs for more details: https://firebase.google.com/docs/database/admin/save-data#section-update

Upvotes: 2

Related Questions