【问题标题】:How to create a document with a subcollection within Firestore cloud function?如何在 Firestore 云功能中创建带有子集合的文档?
【发布时间】:2022-01-21 03:32:06
【问题描述】:

您好,我想通过云函数触发器使用 private 子集合创建以下文档:

这是我到目前为止所拥有的,但不知道如何实际设置子集合。

"use strict";
Object.defineProperty(exports, "__esModule", {value: true});

// Cloud Functions for Firebase SDK to create Cloud Functions + set up triggers.
const functions = require("firebase-functions");

// The Firebase Admin SDK to access Firestore.
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

// Listen to .onCreate trigger
exports.createProfile = functions.auth.user().onCreate((user) => {
  return admin.firestore().doc(`/users/${user.uid}`).set({
    firstName: null,
    lastName: null,
    preferredName: null,
  });
});

【问题讨论】:

    标签: javascript firebase google-cloud-firestore firebase-authentication firebase-security


    【解决方案1】:

    可以通过交替使用collectiondoc 引用来形成对文档的引用。把它拼出来有点过火了......

    const usersCollectionRef = firestore().collection('users')
    const userRef = usersCollectionRef.doc(user.uid);
    const privatesCollectionRef = userRef.collection('private');
    const accountRef = privatesCollectionRef.doc('account');
    
    return accountRef.set(...)
    
    // or, the other extreme lines-of-code-wise
    const accountRef = firestore().doc(`/users/${user.uid}/private/account`)
    return accountRef.set(...)
    

    请注意,您一次只能在“私人”集合中拥有一个名为“帐户”的文档。不确定您的应用的语义,但该文档中用户的电子邮件可能是更好的文档名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2018-05-19
      • 1970-01-01
      • 2019-12-03
      • 2021-02-20
      • 1970-01-01
      • 2018-10-04
      • 2020-05-23
      相关资源
      最近更新 更多