Dalvendra Singh
Dalvendra Singh

Reputation: 85

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

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);
    });

Upvotes: 1

Views: 93

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599551

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.

Upvotes: 1

Related Questions