【问题标题】:How to add a document to a collection in cloud firestore如何将文档添加到云 Firestore 中的集合
【发布时间】:2019-06-04 21:25:12
【问题描述】:

我有一个名为“用户”的集合。我正在尝试在 Google 身份验证后将用户添加到集合中,但我不断收到以下错误:

FirebaseError:[code=invalid-argument]:文档引用无效。文档引用必须有偶数个段,但用户有 1 个。

这里是代码

this.googlePlus.login({
    'scopes': '', 
    'webClientId': environment.googleWebClientId,
    'offline': true,
})
.then(user => {
    // save user data on the native storage
    const userRef: AngularFirestoreCollection<User> = this.afs.collection<User>(`users/`);
    const data: User = {
        email: user.email,
        displayName: user.displayName,
        uid: user.uid
    };
    userRef.set(data)
    .then(() => {
        this.router.navigate(['/home']);

【问题讨论】:

    标签: firebase ionic-framework firebase-authentication google-cloud-firestore


    【解决方案1】:

    您的userRef 指的是一个集合,对象的类型称为CollectionReference。您正在尝试使用一些应该成为该集合中的新文档的对象来调用 set()。但这不是它的工作方式。相反,您似乎想调用 add() 来添加具有新随机 ID 的新文档。

    如果您已经知道新用户文档的 ID,则应该使用该 ID 构建 DocumentReference,然后在该 DocumentReference 上使用 set() 来创建文档。

    【讨论】:

    • 操作是否可以保持userRef 调用其doc() 方法来获取docRef(即使没有id 并且让google 生成一个),然后在该docRef 上调用set 也是正确的吗?
    • 也许,这将特定于 AngularFire,我不太了解。我说的主要是 AngularFire 包装的底层 JS AP。关键是 set() 只能用于文档引用,不能用于集合引用。
    • 当然,任你选。
    • 换句话说,@D.Hodges,另一种方法是将 userRef.set(data) 更改为 userRef.doc().set(data)(也许 DougStevenson 可以在您的“用户/”集合中的尾部斜杠上权衡。我已经从来没见过这样用的)。
    【解决方案2】:

    Google+ is being discontinued 所以您应该查看 Firebase 身份验证,或 GCP's new Cloud Identity Platform

    对于 Firebase 身份验证,您必须监听 .onAuthStateChanged 观察者。一旦它触发了您的 user 对象,您就可以将它写入 Firestore 中的用户集合中。最佳做法是使用firebase.auth().currentUser.uiduid 作为users 集合中的用户文档ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2018-07-30
      • 2022-01-07
      • 2018-07-22
      • 1970-01-01
      相关资源
      最近更新 更多