首页 > 解决方案 > 是否有向 Firebase Firestore 中的所有用户添加唯一 ID 的功能?

问题描述

我有一个具有以下结构的数据库(Firebase - Cloud Firestore)。

users
     |
     unique id (list of unique ids for each user)

数据结构

我想为每个用户分配一个带有另一个唯一 ID 的新字段,用于识别用户。问题是我不知道怎么做。

这是每个用户的当前字段。 当前字段

我试图在 javascript 中创建一个函数,允许我使用 Firebase API 来执行此操作,但无济于事。

async function updateAllUsers(){
   firebase.firestore().collection("users").get()
   .then((users) => {
     users.forEach((user) => {
       writeUserData(user.id)
      // console.log(user.id)
     })
   })
  
}

async function writeUserData(uid){
  const userRef = firestore.doc(`users/${uid}`);
  const snapShot = await userRef.get();
  console.log(uid) --> we get here
  console.log(snapShot.exists) --> we get here, prints true
  if(snapShot.exits){ --> we do not get here
    const userId = uid
    console.log("true if"); --> we do not get here
    try {
      console.log("we updated the id"); --> we do not get here
      await userRef.update({
        userId,
      });
    } catch (error) {
      console.log("error updating user id", error.message);
    }
  }
}

这是上述功能工作的控制台日志。 控制台日志

任何帮助或指向方向肯定会有所帮助。

这是我查看过的文档,但似乎找不到解决方案或指向好的方向。

编辑

@Renaud Tarnec 发现的代码中的错字应该是 snapShot.exists 而不是 snapShot.exits

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


推荐阅读