代码之家  ›  专栏  ›  技术社区  ›  Prince Hamza

javascript:cloud firestore merge正在替换数据

  •  0
  • Prince Hamza  · 技术社区  · 7 年前

    我写数据的初始代码是

    var Cloud = firebase.firestore();
    
      Cloud.collection("IPA").doc("Allipas").set({
        IPlist: "A;B;",   
    })
    .then(function() {
        console.log("Document successfully written!");
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });
    

    然后我想把新的信息合并到我的领域

      var Cloud = firebase.firestore();
    
      Cloud.collection("IPA").doc("Allipas").set({
        IPlist: "C;",   
    } , {merge : true})
    .then(function() {
        console.log("Document successfully written!");
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });
    

    但它只把字段替换为“C”,我看不到A&B

    2 回复  |  直到 7 年前
        1
  •  1
  •   Frank van Puffelen    7 年前

    这个 merge: true 选项将在API调用中提供的字段与文档中的现有字段合并。它不会将单个值与字段的现有值合并。

    如果要更新字段的现有值,必须先读取该字段的值,然后在代码中更新该值,最后将其写回数据库。

    这通常是在事务中完成的,以确保没有其他人可以同时写入冲突的更新。例如:

    var docRef = Cloud.collection("IPA").doc("Allipas");
    Cloud.runTransaction(function(transaction) {
        // This code may get re-run multiple times if there are conflicts.
        return transaction.get(docRef).then(function(doc) {
            if (!doc.exists) {
                throw "Document does not exist!";
            }
    
            var newIPlist = doc.data().IPlist + "C;";
            transaction.update(docRef, { IPList: newIPList });
        });
    }).then(function() {
        console.log("Transaction successfully committed!");
    }).catch(function(error) {
        console.log("Transaction failed: ", error);
    });
    

    请注意,firebase建议不要使用这种组合值或数组,正是因为这个原因:在更新现有值之前必须先读取它,这会降低解决方案的可伸缩性。看看 documentation on working with arrays, list, and sets 作为替代品。

        2
  •  0
  •   Diego Venâncio    7 年前

    您的合并可以更改为更新吗?

    updteSomething() {
            this.db.collection('IPA').doc(Allipas).update({
                IPlist: ""A;B;C;",
            })
                .then(function () {
                    console.log("Document successfully deleted!");
                }).catch(function (error) {
                    console.error("Error removing document: ", error);
                });
        }