如何在flutter中通过没有文档ID的用户ID字段更新文档字段的值?

Posted

技术标签:

【中文标题】如何在flutter中通过没有文档ID的用户ID字段更新文档字段的值?【英文标题】:How can I update value of the field of the document by userID Field without doc ID in the Firebase collection in flutter? 【发布时间】:2022-01-21 21:51:55 【问题描述】:

我想更新字段文档的值。我写了一个查询,但它不起作用。

**//this query is working, I hava a doc Id**
    final CollectionReference _company = FirebaseFirestore.instance
        .collection('Company')
      ..where(FieldPath.documentId, isEqualTo: _auth.currentUser!.uid);


      **// But this query is not working, because I have not doc** ID, its doc ID auto gen. ID in firebase
    final CollectionReference _companyAdvert =

        FirebaseFirestore.instance.collection('CompanyAdvert')..where('userId', isEqualTo: _auth.currentUser!.uid)  ;

all the code here

【问题讨论】:

你好 Zekai,你能改一下你的问题吗?目前还不是很清楚你需要什么 当然。首先感谢您的关心。 我正在开发一个基于 Firebase 的颤振项目。我创建了一个名为“Company”的集合并添加了一个字段 companyImage。公司集合的名称是用户 ID。其他集合名称是 CompanyAdvert。但是 CompanyAdvert 的文档名称是通过自动生成的 ID 创建的。如果公司想要更改其个人资料照片,则必须在 CompanyAdvert profileImage 字段中进行更新。我努力在我的代码中使用 _companyAdvert 变量。但我做不到。最后我该怎么做,对不起我的英语不好.. drive.google.com/file/d/1bFot-59FcOU130BR8ADg07uONy7vSTLI/… @ZekaiDemir 您可以编辑您的问题并重新调整它的阶段,不要发表评论。 【参考方案1】:

要更新 firestore 中的文档字段,您需要编写

await FirebaseFirestore.instance
    .collection('CompanyAdvert')
    .doc(id)
    .update( 'profileImage': *new profile image* );

您必须了解,要更新 Firestore 文档,您必须在文档本身中保留文档 ID 的引用。您可以将其视为文档的主键。 有两种方法可以做到这一点。

1. Get a reference to the newly created document, and then get the id from the reference. 
   Then update the document with this id

2. Generate a random id locally and use that as the document id.
   You can do this with the [Uuid package][1] on pub.dev

第一步是这样的:

// first, create a document using the add method

DocumentReference docRef = await FirebaseFirestore.instance
    .collection('CompanyAdvert')
    .add(*data*);

// then extract the generated document id

String id = docRef.id;

// then save it back to the document using

await FirebaseFirestore.instance
    .collection('CompanyAdvert')
    .doc(id)
    .update('id': id);

第二步是这样的:

String id = const Uuid().v4();

await FirebaseFirestore.instance.collection('CompanyAdvert').doc(id).set(*data*);
// Make sure you add the id as one of the fields to the map data

请注意,第一步会产生写入操作,这将计入您的 firebase 总配额。我建议你使用第二种方法

访问FlutterFire documentation了解更多信息

【讨论】:

我试过了,但我的 firebase 文档已经创建了,但它不起作用。是否有没有文档 ID 的更新字段? 不,您需要一个 ID 来更新任何文档

以上是关于如何在flutter中通过没有文档ID的用户ID字段更新文档字段的值?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 discord.js 中通过 id 查找用户

在 Laravel 中通过用户 ID 强制注销特定用户

如何在 Flutter 中从 Firebase Auth 获取用户 ID?

如何在laravel中通过id选择不同表上的关系数据

currentuser 如何在flutter中通过fcm向另一个用户发送请求通知?

如何在 Flutter 中从 Firebase 获取当前用户 ID