Sam Yoon
Sam Yoon

Reputation: 93

Firebase document reference field gets set as string field type instead of reference field type

Problem: User reference field set as string field type instead of reference field type.

Context: When a new user is created, the below function should create a new document in a collection called "Workout Cycles" in Firebase. The new user document is created and the Workout Cycles document is created, but the "user" field (which is the aforementioned user reference) is populated as a string and not as a reference. See example of newly created Workout Cycles document with user field set as string here: Example of document with "user" field set as string instead of reference

How the user field is currently set: I am using const userDocReference = snap.id; to capture the UID of the user that was created and storing it in userDocReference. Once stored, I use the set() command to create the new Workout Cycles document in Firebase. I am currently setting the user field with user: userDocReference, within the set() command to assign the .

Here is the function code:

import functions = require("firebase-functions");
require("firebase-functions");

import admin = require("firebase-admin");
require("firebase-admin");


admin.initializeApp();

"use strict";

functions.logger.debug("debug level in web console and gcp");
functions.logger.log("info level in web console and gcp");
functions.logger.info("info level in web console and gcp");
functions.logger.error("error level in web console and gcp");

exports.createWorkoutCycle = functions.firestore
    .document("users/{userId}")
    .onCreate((snap, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const date = new Date();
      const dateString = date.toString();
      const userDocReference = snap.id;
      return admin.firestore().collection("WorkoutCycles").doc().set({
        name: "New Workout Cycle",
        createTimestamp: dateString,
        user: userDocReference,
      });
    });

Upvotes: 0

Views: 411

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317750

snap.id is indeed a string with the ID of the users document and not a reference, so this code is behaving correctly as you've described.

If you instead want a reference to the users document, it might be helpful to know that snap is a DocumentSnapshot object. It has a ref property which is a DocumentReference.

const userDocReference = snap.ref;

It's also conventional not to store dates as strings and instead use a Firestore timestamp, which makes it possible to sort the documents chronologically. Simply use a JavaScript Date object to get that behavior.

Upvotes: 2

Related Questions