【问题标题】:how to avoid duplicates on firebase firestore web sdk [duplicate]如何避免在firebase firestore web sdk上重复[重复]
【发布时间】:2020-10-27 18:13:14
【问题描述】:

我正在为已登录的用户创建个人资料。我遇到的问题是,在某些情况下允许为给定的 uid 创建重复的配置文件,而不是返回已经存在的配置文件。

const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
    if (user) {
        findProfile(user.uid)
            .then((profile) => console.log(profile))
            .catch((error) => createProfile(user.uid))
    } else {
        console.log("user not signed in")
    }
});

export const findProfile = (uid) => {
    return firebase
        .collection("profiles")
        .where("uid", "==", uid)
        .get()
        .then((querySnapshot) => {
            if (querySnapshot.size > 0) {
                return querySnapshot.docs[0];
            } else {
                throw new Error("profile not found");
            }
        });
};

export const createProfile = (uid) => {
    return firebase.collection("profiles").add({uid});
};

【问题讨论】:

    标签: javascript firebase google-cloud-firestore firebase-authentication


    【解决方案1】:

    Firebase 身份验证 UID 是唯一的。鉴于它们是唯一的,您可以将其用作“配置文件”中文档的 ID,而不是接受使用 add() 获得的随机 ID。因此,您应该改用 set() 并在要创建的文档的路径中指定 UID。这将大大简化您的读写代码。

    firebase.collection("profiles").doc(uid).set({...})
    

    请注意,如果文档已经存在,set() 会像这样失败,所以你也应该检查一下。

    获取文档就是这样:

    firebase.collection("profiles").doc(uid).get()
    

    【讨论】:

    • 这完全有道理,但不幸的是,现在我有数千个带有你提到的随机 ID 的个人资料。需要找到解决重复问题的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2018-03-15
    • 2021-08-17
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多