【问题标题】:Flutter Firestore add new document with Custom IDFlutter Firestore 添加具有自定义 ID 的新文档
【发布时间】:2019-08-15 03:58:02
【问题描述】:

如何使用 Dart 和 Flutter 添加具有自定义 id 的新文档?

PS:我可以将新文档添加到集合中,但它的 id 随机设置,使用此代码

postRef.add(data);

其中postRefCollectionReferencedataMap<String, dynamic>

【问题讨论】:

    标签: dart flutter google-cloud-firestore


    【解决方案1】:

    您可以使用set() 函数代替add()

    这里是完整的代码:

    final CollectionReference postsRef = Firestore.instance.collection('/posts');
    
    var postID = 1;
    
    Post post = new Post(postID, "title", "content");
    Map<String, dynamic> postData = post.toJson();
    await postsRef.doc(postID).set(postData);
    

    希望对大家有所帮助。

    【讨论】:

    • 可以创建autoID吗?
    • 是的,当然,您可以使用await postsRef.add(postData);,这就是问题所在!
    • 我们从哪里带来 '.toJson();' ??它没有定义并且会很酷,而不是我没有做的是我把每个类都像 Post() 并将它的字段映射到一个映射中,如果 .toJson();自动工作会很酷,我可以从哪里导入?或者我只是像我已经在做的那样定义那个函数?
    • @RagehElAzzazy 这是我在 tge 类中定义的一种方法,用于返回带有我想要的字段的键的映射。我的代码和你的代码没有区别,只是类中的方法。
    • @Shady Boshra,我也做了同样的事情,谢谢伙计,teslam ya m3allem
    【解决方案2】:

    2021 年更新:

    不要使用add,而是在文档上使用set

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('doc_id') // <-- Document ID
        .set({'age': 20}) // <-- Your data
        .then((_) => print('Added'))
        .catchError((error) => print('Add failed: $error'));
    

    【讨论】:

      【解决方案3】:
      String uniqueCode = //Your Unique Code
      DocumentReference reference = Firestore.instance.document("test/" + uniqueCode );
      
      //Setting Data
      Map<String, String> yourData;
      reference.setData(yourData);
      

      【讨论】:

      • 这也可以,但如果它是一个共享数据库,我建议通过使每个事务原子性来处理原子性,如下所示Firestore.instance.runTransaction((Transaction tx) async { await _firestoreRef.setData(data); });
      【解决方案4】:

      您可以尝试使用此代码插入带有 customID 的新文档

          DocumentReference<Map<String, dynamic>> users = FirebaseFirestore
                    .instance
                    .collection('/users')
                    .doc("MyCustomID");
                var myJSONObj = {
                  "FirstName": "John",
                  "LastName": "Doe",
                };
                users
                    .set(myJSONObj)
                    .then((value) => print("User with CustomID added"))
                    .catchError((error) => print("Failed to add user: $error"));
      

      【讨论】:

        猜你喜欢
        • 2018-07-10
        • 2019-02-27
        • 2022-01-21
        • 1970-01-01
        • 2021-10-04
        • 2019-05-04
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        相关资源
        最近更新 更多