代码之家  ›  专栏  ›  技术社区  ›  Daibaku

flatter Firestore update if exist if not create如果存在,则创建

  •  3
  • Daibaku  · 技术社区  · 7 年前

    我想知道是否存在特定的文件,更新该文件,如果没有创建该文件是在Firestore或不可能。
    Firestore.instance.collection('tags').document(tag here).updateData() 如果文档不存在,有没有办法创建一个方法,或者在写之前我必须检查它是否存在?

    2 回复  |  直到 7 年前
        1
  •  9
  •   Doug Stevenson    7 年前

    看到了吗 documentation 例如其他语言的例子。可能只是路过的问题 { merge: true } SetOptions.merge()

        2
  •  25
  •   Ezra Alberto Millan    5 年前

    更新

    FirebaseFirestore.instance.
      collection('tags').
      document(tag).
      set(data, SetOptions(merge: true))
    

    @Doug是对的,在Flatter Firestore API中有一个选项:

    Firestore.instance.
      collection('tags').
      document(tag here).
      setData(data, merge: true)
    

    setData(Map<String, dynamic> data, {bool merge: false}) → Future<void>

    写入此DocumentReference引用的文档。如果文档尚不存在,将创建它。

    合并 如果为true,则提供的数据将合并到现有文档中,而不是覆盖。

    updateData ,显式失败。

    updateData(Map<String, dynamic> data) → Future<void>

    如果还没有文档,更新将失败 .

        3
  •  3
  •   WillHaslett    5 年前

    从2020-03-31开始,是的,您必须首先检查文档是否存在。 setData(data, merge: true) 不遵守法律 merge Here is the relevant GitHub issue

    我的行为相当于 setData() ,因此它会自动覆盖所有现有数据。昂贵的解决方法:

    final Firestore _db = Firestore.instance;
    final collection = 'my_collection';
    final documentId = 'my_document';
    final snapShot = await _db.collection(collection).document(documentId).get();
    if(snapShot.exists){
      _db.collection(collection).document(documentId).updateData(myMap);
    } else {
      _db.collection(collection).document(documentId).setData(myMap);
    }
    
        4
  •  0
  •   Haider Malik    5 年前

    Future updateUserFirestore(
      String name,
      String dob,
      String email,
      String sex
    ) {
    
        return _getUserDetailsDocumentRef().update({
          'name': name,
          'dob': dob,
          'email': email,
          'sex': sex
        }).catchError((e) => {
    
          _getUserDetailsDocumentRef().set({
            'name': name,
            'dob': dob,
            'email': email,
            'sex': sex
          }, SetOptions(merge: true))
        });
    }