How I can add new field in coming firebase snapshot of onWrite() firebase cloud method

Viewed 22

I have tried with set and setvalue() methods. I want to add document_id field in coming snapshot here is my code.

const admin = require('firebase-admin');
const functions = require('firebase-functions');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
admin.initializeApp();
const db = getFirestore();

exports.locationUpdateListener = functions.region('asia-south1').firestore
    .document('location/{locationId}')
    .onWrite((change, context) => {
        const data = change.after.data();
        const timeMilli = process.hrtime.bigint();
        const id = data.mobile + '_' + timeMilli;

        data.set({ 'document_id': id });//here I need to add document_id field into data.

        db.doc('history_location/' + id).set(data);
    });
1 Answers

If you set the new field to data it just exists in the current code. To persist the value, you will have to write it back to Firestore with something like this:

exports.locationUpdateListener = functions.region('asia-south1').firestore
.document('location/{locationId}')
.onWrite((change, context) => {
    const data = change.after.data();
    const timeMilli = process.hrtime.bigint();
    const id = data.mobile + '_' + timeMilli;

    // 
    if (data.document_id !== id) {
        change.after.ref.update({ 'document_id': id });
    }

    db.doc('history_location/' + id).set(data);
});

Don't forget the condition I added, as otherwise you'll end up with an endless loop.

Related