【发布时间】:2026-01-29 14:25:03
【问题描述】:
将数据从云 Firestore 提取到 javascript 中的变量中是可行的吗? 我有两个集合,第一个叫做“聊天”,有文档“created_at”、“messege”和“用户名”。
第二个集合称为“用户”,只有一个名为“用户名”的文档,其中包含用户在登录时创建的用户名。
所以我的想法是将用户名从集合“用户”传递到集合“聊天”中的“用户名”,以便在像这样的类中使用它
class Chatroom {
constructor(room, username) {
this.room = room;
this.username = username;
this.chats = db.collection("chats");
}
async addChat(message) {
const now = new Date();
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now),
};
const response = await this.chats.add(chat);
return response;
}
getChats(callback) {
this.chats.orderBy("created_at").onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
callback(change.doc.data());
}
});
});
}
updateName(username) {
this.username = username;
}
}
我正在考虑做这样的事情,因为我在代码的另一部分做了同样的事情,只是为了显示登录信息并且它的工作。但我不知道如何从函数中获取用户名数据以便在课堂上再次使用它。
let getTheuser = (user) => {
if (user) {
db.collection("users")
.doc(user.uid)
.get()
.then((doc) => {
username = doc.data().username;
});
}
};
【问题讨论】:
标签: javascript firebase google-cloud-firestore firebase-authentication