我有一个方法,它返回一个我知道肯定指向文档的字符串。使用该字符串时如下:
const docRef = "users/uid/data/online"
const dbPath = db.doc(docRef)
console.log(dbPath.path)
return dbPath.set({"test" : 1})
失败了:
如果我使用db.collection("用户")。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
})
答案 0 :(得分:1)
您可能还想在/users
集合以及online
子集合中创建文档。否则,您将最终获得孤立的集合。我已经添加了一些代码来批处理。
您可以从user
事件中获取许多其他详细信息,您可以将其保存在文档中,例如电子邮件,姓名,photoURL等。
我不确定这是否是您正在寻找的,但它应该做您需要的。
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的函数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}`;