Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I populate the reference Field using Firestore

Do you know how I can populate the reference Field on a Document using Firestore?

Firestore

like image 983
Igor Ronner Avatar asked Dec 24 '22 09:12

Igor Ronner


1 Answers

When you create / get a document reference, you can save this into another document. This example is for the Node SDK, but it should give you an idea of how to implement this for Android.

Creating a document reference

// Create the references
let myFirstDoc = db.collection('myCollection').doc();
let mySecondDoc = db.collection('otherCollection').doc();

let batch = db.batch();

// Save the two documents to the batch
batch.set(myFirstDoc, {someData: true});
batch.set(mySecondDoc, {firstDocRef: myFirstDoc});

// Commit the batch
return batch.commit()
  .then(response => {
    console.log('Data saved');
  })
  .catch(err => {
    console.error(err);
  });

Getting an existing reference

return db.collection('myCollection').doc('myDocId')
  .then(documentSnapshot => {
    let newDoc = db.collection('otherCollection').add({otherDoc: documentSnapshot.ref});
  })
  .then(response => {
    console.log('Data saved');
  })
  .catch(err => {
    console.error(err)
  })
like image 193
Jason Berryman Avatar answered Dec 28 '22 08:12

Jason Berryman