【问题标题】:Pass data from cloud firestore into a variable将数据从 Cloud Firestore 传递到变量中
【发布时间】: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


    【解决方案1】:

    如果我正确理解了您的问题,您希望通过getTheuser() 函数获取username,并使用生成的用户名创建Chatroom() 类的实例。

    您首先需要在 getTheuser() 函数中返回您通过 Firestore 查询获得的值:

    let getTheuser = (user) => {
      if (user) {
        return db.collection("users")
          .doc(user.uid)
          .get()
          .then((doc) => {
            return username = doc.data().username;
          });
      } else {
        return null;
      }
    };
    

    请注意,getTheuser() 函数是异步的,因此您需要使用 then() 或 async/await。所以以下应该可以解决问题:

    const myUser = ....; // an Object having a uid property
    const myRoom = ...;
    
    getTheuser(myUser)
    .then(username => {
      if (username) {
        const myChatroom = new Chatroom(myRoom, username);
        // ...
      } else {
        // ...
      }
    })
    

    【讨论】:

    • 我得到了第一部分,但在第二部分中,我不明白我必须将代码放在“聊天室”类的哪个部分,因为当“const”myUser 和 myRoom 是created 我不知道传递了什么值
    • 第二部分展示了如何获取用户名值并使用它来创建类的实例。你不应该在课堂上使用它。或者我完全误解了你的目标。
    • 嘿@Alan,您有时间进一步查看建议的答案吗?
    • 你好@Renaud 它的工作!抱歉耽搁了我的一些问题,非常感谢!
    【解决方案2】:

    我知道它不能直接回答你的问题,但我认为你需要考虑一切是如何连接的。

    这就是我组织工作流程的方式。

    这是伪代码,只是一个建议。这可能不是最好的,但这是我现在能想到的。

    class Room {
      constructor ({ id, name }) {
        this.id = id // || genId() // if no id is provided than generate a unique id
        this.name = name
        this.chat = []
      }
    
      static async getRooms () {
        // get rooms from database and instantiate data with Room class
      }
    
      async getChats () {
        // get room chat from database (filter with roomId)
        // dont forget to instantiate data with Chat class + assign list to this.chat array
      }
    
      listenForChats (cb) {
        // use onSnapshot on chat filter by roomId and return callback
      }
      
      sendChat (chat, user) {
        // set roomId, userId and use chat.create()
      }
    
      async create () {
        // check if not already in database
        // add to database
      }
    
      async destroy () {
        // remove from database
      }
    }
    
    class Chat {
      constructor ({ id, userId, roomId, message }) {
        this.id = id // || genId()
        this.user
      }
    
      async create () {
        // add to database
      }
    
      async destoy () {
        // remove from database
      }
    }
    
    class User {
      constructor ({ id, username }) {
        this.id = id // || genId()
        this.username = username
      }
    
      static async getAllUsers () {
        // get users from database and instantiate data with User class
      }
    
      static async getUser (id) {
        // get specific user from database and instantiate data with User class
      }
    
      async getChats () {
        // get chat of users from database
      }
    
      async create () {
        // check if not already in database
        // add to database auto assign id
      }
    
      async destroy () {
        // remove from database
      }
    }
    
    // Usage
    const users = await User.getAllUsers()
    
    const room = new Room({ name: 'test' })
    await room.create()
    
    const firstUser = users[0]
    
    // Send message like this
    const chat = new Chat({ userId: firstUser.id, roomId: room.id, message: 'hello' })
    await chat.create()
    
    // or
    const chat = new Chat({ message: 'hello' })
    room.sendChat(chat, firstUser)
    

    当然,您可以向您的类添加更多功能,例如:静态异步 getRoom(id) 并返回使用数据库中的数据实例化的 Room 对象。

    【讨论】: