Home > Blockchain >  Firestore: Adding Document ID to custom class
Firestore: Adding Document ID to custom class

Time:12-20

long-time listener, first-time caller -- also new to javascript and Firebase, so be kind lol

I'm working on a personal project, and I've successfully created a custom class/converted. I want to add the document ID to that class, but I haven't been able to figure that out. Is there an easy way to include that element to this class?

class Merit {
    constructor(book, cost, effect, name, page, prereq, style, tags, tldr, id){
      this.book = book;
      this.cost = cost;
      this.effect = effect;
      this.name = name;
      this.page = page;
      this.prereq = prereq;
      this.style = style;
      this.tags = tags;
      this.tldr = tldr;
    } 

  const meritConverter = {
    fromFirestore: (snapshot, options) => {
      const data = snapshot.data(options);
      return new Merit(
        data.book,
        data.cost,
        data.effect,
        data.name,
        data.page,
        data.prereq,
        data.style,
        data.tags,
        data.tldr
      );
    },
  };

CodePudding user response:

Use the id property of the DocumentSnapshot:

  const docId = snapshot.id;

And in your code:

class Merit {
    constructor(book, cost, effect, name, page, prereq, style, tags, tldr, id){
      this.book = book;
      this.cost = cost;
      this.effect = effect;
      this.name = name;
      this.page = page;
      this.prereq = prereq;
      this.style = style;
      this.tags = tags;
      this.tldr = tldr;
      this.id = id;
    } 

  const meritConverter = {
    fromFirestore: (snapshot, options) => {
      const data = snapshot.data(options);
      return new Merit(
        data.book,
        data.cost,
        data.effect,
        data.name,
        data.page,
        data.prereq,
        data.style,
        data.tags,
        data.tldr,
        snapshot.id
      );
    },
  };
  • Related