Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a document in Firestore that includes a reference to an existing document in another collection

I'm attempting to post new documents to a collection which contain references to existing documents.

Here is my code:

var admin = require('firebase-admin');
var serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://DBURL.firebaseio.com'
});

var db = admin.firestore();

db.collection('myFunCollection').add({
  someBool: false,
  someNumber: 13.2,
  video: 'videos/Izdm35CsW6kqv2UxZEX0',
  user: 'users/pb7La4kzEaBow4iWvmxZ'
});

video and user reference existing documents in other collections, but when I run this code, the fields are stored as strings rather than references. The documentation notably does not describe how to do this.

How can I post these values as references?

like image 582
chenware Avatar asked May 26 '18 17:05

chenware


People also ask

Can a document contain another collection in firebase?

A collection contains documents and nothing else. It can't directly contain raw fields with values, and it can't contain other collections.

How do you create a reference for a document?

Citation includes author's name, year of publication, then page numbers if available. If your source lacks an author, cite the first one or two words of the title. If no date is given, place "n.d." after the author's name. note on page numbers: Web documents often don't have page numbers.


1 Answers

Figured it out – by using "db.doc('{path}')"

var admin = require('firebase-admin');
var serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://DBURL.firebaseio.com'
});

var db = admin.firestore(); 

db.collection('myFunCollection').add({
  someBool: false,
  someNumber: 13.2,
  video: db.doc('videos/Izdm35CsW6kqv2UxZEX0'),
  user: db.doc('users/pb7La4kzEaBow4iWvmxZ')
});
like image 128
chenware Avatar answered Sep 28 '22 03:09

chenware