How do you insert a "reference" value into firestore?

AskYous picture AskYous · Jul 11, 2018 · Viewed 20.7k times · Source

I'm trying to insert a document into a collection. I want the document to have a attribute of type reference to insert into the collection. But every time I insert into the collection, it comes out as a string or an object. How can I programmatically insert a reference typed value?

enter image description here


It's definitely possible to do it in the UI:

enter image description here

Answer

trojek picture trojek · Jan 22, 2019

Probably the simplest solution is to set the value of a reference key to a doc(collection/doc_key) because a DocumentReference is needed.

Example code:

post = {
  content: "content...",
  title: "impressive title",
  user: db.doc('users/' + user_key),
};

db.collection('posts').add(post)