Divya Galla
Divya Galla

Reputation: 513

Cloud Functions that add a new collection to the already existing document in firestore

I want to add new collection to a doc that already exists in firestore.Is it possible? The following is the code for doing that, I used cloud fucntions for doing that.Whenever a document is created in firestore then the following cloud function has to trigger

const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.myWallet = functions.firestore
    .document('Samyata/{authid}')
        .onCreate(event =>{
        const ID = event.params.authid
        const db = admin.firestore();
        var data = {
        Bitcoins : '0',
        Ether : '0',
        deyaCoins : '0'
        };
        var docRef = db.collection('Samyata').doc(ID);
        var updateDoc = docRef.update({
        db.collection('Samyata').doc(ID).collection('Wallet').doc(ID).set(data);});
        //var updateRef = docRef.update();
        });//end of onCreate() 

Upvotes: 2

Views: 3024

Answers (3)

Gene
Gene

Reputation: 11267

transactionData= {
   TimeStamp: "123",
   SomeBooleanValue: false
}


var addDocToNewCollResult= admin.firestore().collection('CollectionLevel1').doc(userID).collection('CollectionLevel2').doc(transactionID).collection('CollectionLevel3').doc("OtherID").set( transactionData );

Upvotes: 0

Inti Mateo
Inti Mateo

Reputation: 46

or you can concatenate the path like this

return db.collection(`Samyata/${ID}/Wallet/${ID}`).add(data)

Upvotes: 1

Skye
Skye

Reputation: 1469

Try this :)

return db.collection('Samyata').doc(ID).collection('Wallet').doc(ID).set(data);

Upvotes: 5

Related Questions