【问题标题】:Initialize documentReference through string fails通过字符串初始化 documentReference 失败
【发布时间】:2018-04-18 19:51:57
【问题描述】:

我有一个方法可以返回一个我知道肯定指向文档的字符串。如下使用该字符串时:

const docRef = "users/uid/data/online"
const dbPath = db.doc(docRef)
console.log(dbPath.path)
return dbPath.set({"test" : 1})

失败了:

如果我使用 db.collection("users").doc(uid)...... 它可以工作。如何通过 typescript 中的字符串创建文档引用?

它应该根据文档工作:https://firebase.google.com/docs/firestore/data-model#references

编辑:这是我的课:

export enum UserCollection {
    online = "online",
    private = "private",
    server = "server"
}

export enum UserDocument { 
    online = "online",
    private = "private",
    server = "server"
}

class ManagerPath { 

    pathToUser = "users/"

    getPathToUser(uid: string, userCollection: UserCollection, userDocument: UserDocument): string { 
        return this.pathToUser + "/" + uid + "/" + userCollection + "/" + userDocument;
    }

}

export const managerPath = new ManagerPath();

这就是我检索路径的方式:

exports.initializeNewUser = functions.auth.user().onCreate((user) => {
    const test = managerPath.getPathToUser(user.uid, UserCollection.online, UserDocument.online);
    console.log(test)
    const dbPath = db.doc(test)
    return dbPath.set({"dateCreation" : Date.now()}) //fails
})

【问题讨论】:

  • 你从哪里得到路径字符串?你是如何创造它的?它是现有文档中的字段吗?知道从哪里获取构建字符串所需的变量会很有用。
  • @JasonBerryman 我编辑了我的问题

标签: firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

您可能还想在/users 集合以及online 子集合中创建一个文档。否则,您将得到一个孤立的集合。我已经添加了一些代码来批量执行此操作。

您可以从user 事件中获得许多其他详细信息,您可以将其保存在文档中,例如电子邮件、姓名、照片URL 等。

我不确定这是否是您正在寻找的,但它应该可以满足您的需求。

exports.initializeNewUser = functions.auth.user().onCreate((user) => {
    const userRef = db.doc(`users/${user.uid}`);
    const userOnlineRef = db.doc(`users/${user.uid}/online/online`);
    const dateCreation = user.metadata.creationTime;

    let batch = db.batch();
    batch.create(userRef, {dateCreation})
    batch.create(userOnlineRef, {dateCreation})
    return batch.commit();
})

需要 >= 1.0.0 的 Functions SDK

修复您的代码

您已将您的pathToUser 声明为"users/",然后添加了另一个/。您可以通过修改以下行来解决此问题

return this.pathToUser + "/" + uid + "/" + userCollection + "/" + userDocument;

return this.pathToUser + uid + "/" + userCollection + "/" + userDocument;

pathToUser = 'users'; // The trailing / has been removed

return `${this.pathToUser}/${uid}/${userCollection}/${userDocument}`;

【讨论】:

  • 嗨杰森,我真的不明白这如何回答我的问题。我想通过字符串创建文档引用,而不使用“.collection()”。文档说这是可能的,但我得到一个错误。我的目标是从 ManagerPath 类中检索路径,然后更新给定的路径,这是一个文档引用。
  • 我已经更新了我的答案,以消除 collection 属性的必要性。但是,我还看到您的代码中有 2 x /。我也会将此添加到我的答案中。
  • 我为您的代码添加了修复,以及我推荐的使用批处理的代码
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2018-10-03
  • 2016-03-25
  • 2012-11-17
相关资源
最近更新 更多