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

Firestore方法docRef.set之间的差异(someData{merge:true})和docRef.update(someData)?

  •  0
  • cbdeveloper  · 技术社区  · 7 年前

    假设我在Firestore中存储了以下文档。

    collection: "myColection"
      document: "myDocument"
        fields:
          someBoolean: true
          someArray: ['a','b','c']
          etc
    

    Firebase DOCS - Source

    问题

    使用以下方法切换 someBoolean 字段:

    方案1

    const docRef = db.collection('myCollection').doc('myDocument');
    
    await docRef.set({
      someBoolean: false
      }, 
    {merge: true});
    
    

    方案2

    const docRef = db.collection('myCollection').doc('myDocument');
    
    await docRef.update({
      someBoolean: false
    });
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   Renaud Tarnec    7 年前

    如果你已经有了 myDocument myCollection 收藏不会有什么区别。

    文件: set() update()

    看医生 https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#update ,表示“如果应用于不存在的文档,则更新将失败。”

        3
  •  1
  •   andresmijares    7 年前
    • set

    • 设置 具有 { merge: true } 将更新文档中的字段,如果找不到则创建

    • update 将更新字段,但如果文档不存在,将引发错误

    一个重要的细节是,使用set必须提供路径:

    set({ foo: { bar: { baz: true } } }, { merge: true })
    

    更新,这就够了

    update({
      'foo.bar.baz': true
    })
    
        4
  •  0
  •   Ace    7 年前