如何使用 doc 和 firestore 与 @angular/fire/firestore 访问数据库并插入记录

问题描述 投票:0回答:1

我一直在尝试使用以下代码将用户添加到firestore,然后在数据库中添加用户记录。
我已经能够添加用户并收到适当的回报,但是

doc(this.firestore, `users/${credentials.user.uid}`);

我收到错误

因 FirebaseError 失败:[code=invalid-argument]:预计 collection() 的第一个参数是 CollectionReference、DocumentReference 或 FirebaseFirestore。

import { Injectable } from '@angular/core';
import {Auth,createUserWithEmailAndPassword,sendPasswordResetEmail,signInWithEmailAndPassword,     signOut} from '@angular/fire/auth';
import { doc, Firestore } from '@angular/fire/firestore';
import { setDoc } from '@firebase/firestore';

constructor(private auth: Auth, private firestore: Firestore) { 
}


async register({ email, password }: { email: string; password: string }) {
  try {
    const credentials = await createUserWithEmailAndPassword(
      this.auth,
      email,
      password
    ); // returns uid and access tokens etc..
  
    const ref = doc(this.firestore, `users/${credentials.user.uid}`);  // get a document reference
    // fail with FirebaseError: [code=invalid-argument]: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

    setDoc(ref, { email });// set to referenced document 
    return credentials;    
  } catch (e) {
     return null;    
   }

}

我尝试从文档中准确复制:

https://github.com/angular/angularfire

 import { doc, collection } from '@angular/fire/firestore'; // doc collection fail, it seems and get or insert into the database fails

我仍然收到同样的错误。有没有人有使用 angularfire 7.6.1 与 ionic 7 和电容器 5 的经验,或者知道引用最新 ionic 版本的 Firebase 文档的示例

google-cloud-firestore angularfire
1个回答
0
投票

您看到的错误消息 FirebaseError: [code=invalid-argument]: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore 表示传递给 collection() 函数的第一个参数不是预期的类型。当 firestore 对象未正确初始化或它不是 FirebaseFirestore 的实例时,可能会发生此错误。

在您的代码中,您使用 @angular/fire/firestore 模块中的 Firestore 类来创建 firestore 对象的新实例并将其传递给 doc() 函数。但是,该对象可能未正确初始化或者它不是 FirebaseFirestore 的实例。

一种可能的解决方案是确保您从 @angular/fire/firestore 模块导入和使用正确的类和函数。您可以尝试从 @angular/fire/firestore 模块导入 getFirestore 函数,并使用它创建 firestore 对象的新实例,如下所示:

import { getFirestore } from '@angular/fire/firestore';

// ...

constructor(private auth: Auth) {
  this.firestore = getFirestore();
}

// ...

希望这有帮助, Und3罚款

© www.soinside.com 2019 - 2024. All rights reserved.