使用onSnapshot复制数据

时间:2019-05-29 11:31:05

标签: jquery firebase bootstrap-4 google-cloud-firestore bootstrap-modal

我正在使用引导程序模式将数据添加到Cloud Firestore 我希望表格在模式关闭时更新数据

HTML用于模式按钮

<div class="modal-footer">

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button id="submitStudent" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>

JavaScript

$( document ).ready(function(){

    //call the firebase.app namespace and store it to the the constant app
    const app = firebase.app();
    //log detail to console. 
    // not required but does allo the testing to see if the app is working
    console.log(app);
    //load the firebase db into the constant DB
    const db = firebase.firestore();


//JQUERY FOR GETTING A STUDENT DETAILS AND OUTPUTTING TO TABLE:


        db.collection("students").onSnapshot(function(querySnapshot) {

        querySnapshot.forEach(function(doc) {

            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
            let student = doc.data();
            // pull the student data into the table, the escape characters between each set of data denote a new unit
            // currently this is handed pulled from the DB, however it would be better to use a for loop

            $('#overallDashboard > tbody:last-child').append(

                    '<tr> \
                        <th scope="row">'+doc.id+'</th> \
                         <td>'+student.first_name+'</td> \
                         <td>'+student.last_name+'</td> \
                         \
                         <td>'+student.UnitGrades.IT1.CG+'</td> \
                         <td>'+student.UnitGrades.IT1.PG+'</td> \
                         <td>'+student.UnitGrades.IT1.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT2.CG+'</td> \
                         <td>'+student.UnitGrades.IT2.PG+'</td> \
                         <td>'+student.UnitGrades.IT2.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT3.CG+'</td> \
                         <td>'+student.UnitGrades.IT3.PG+'</td> \
                         <td>'+student.UnitGrades.IT3.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT6.CG+'</td> \
                         <td>'+student.UnitGrades.IT6.PG+'</td> \
                         <td>'+student.UnitGrades.IT6.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT8.CG+'</td> \
                         <td>'+student.UnitGrades.IT8.PG+'</td> \
                         <td>'+student.UnitGrades.IT8.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT9.CG+'</td> \
                         <td>'+student.UnitGrades.IT9.PG+'</td> \
                         <td>'+student.UnitGrades.IT9.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT12.CG+'</td> \
                         <td>'+student.UnitGrades.IT12.PG+'</td> \
                         <td>'+student.UnitGrades.IT12.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT13.CG+'</td> \
                         <td>'+student.UnitGrades.IT13.PG+'</td> \
                         <td>'+student.UnitGrades.IT13.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT15.CG+'</td> \
                         <td>'+student.UnitGrades.IT15.PG+'</td> \
                         <td>'+student.UnitGrades.IT15.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT17.CG+'</td> \
                         <td>'+student.UnitGrades.IT17.PG+'</td> \
                         <td>'+student.UnitGrades.IT17.TG+'</td> \
                         \
                         <td>'+student.UnitGrades.IT21.CG+'</td> \
                         <td>'+student.UnitGrades.IT21.PG+'</td> \
                         <td>'+student.UnitGrades.IT21.TG+'</td> \
                         \
                         <td>Calc</td> \
                         <td>Calc</td> \
                         <td>Calc</td> \
                     </tr>' 


                     );//close append



    }); //end for each loop
});//end onsnapshot



    // JQUERY CODE FOR ADDING A STUDENT

    // form for submitting function
    $("#submitStudent").click(function (event) {



        const db = firebase.firestore();
        console.log(db);

        //search document IDs in database
        let student = db.collection("students").doc($("#addStudentNumber").val());

            // add students to the DB
            student.get().then(function(doc) {
                if (doc.exists) {
                    console.log("Document already exists:", doc.data());


                } else {
                    // doc.data() will be undefined in this case
                    console.log("No such document!");

                    student.set({
                    "first_name": $("#addStudentFirstName").val(),
                    "last_name": $("#addStudentLastName").val(),
                    "DOB": $("#addStudentDOB").val(),
                    "completion_year": $("#addStudentCompletionYear").val(),
                    "student_number": $("#addStudentNumber").val(),
                    "student_email": $("#addStudentEmail").val(),
                    "UnitGrades":{ 
                        "IT1": { 
                            "id":"IT1",
                            "name":"Fundamentals of IT",
                            "type":"Exam",
                            "GLH":90,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        }, 
                        "IT2": { 
                            "id":"IT2",
                            "name":"Global Information",
                            "type":"Exam",
                            "GLH":90,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT3": { 
                            "id":"IT3",
                            "name":"Cyber Security",
                            "type":"Exam",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT6": {
                            "id":"IT6",
                            "name":"Appilication Design",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT8": { 
                            "id":"IT8",
                            "name":"Project Management",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT9": { 
                            "id":"IT9",
                            "name":"Product Development",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT12": { 
                            "id":"IT12",
                            "name":"Mobile Technology",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT13": { 
                            "id":"IT13",
                            "name":"Social Media and Digital Marketing",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT15": { 
                            "id":"IT15",
                            "name":"Games Design and Prototyping",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT17": {
                            "id":"IT17",
                            "name":"Internet of Everything",
                            "type":"CWK",
                            "GLH":60, 
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        },
                        "IT21": { 
                            "id":"IT21",
                            "name":"Web Design and Prototyping",
                            "type":"CWK",
                            "GLH":60,
                            "CG": "F",
                            "PG": "F",
                            "TG": "F"
                        }
                    }
                    })
                    .then(function() {
                        console.log("Document successfully written!");

                    })
                    .catch(function(error) {
                        console.error("Error writing document: ", error);
                    });
                }

                }).catch(function(error) {
                    console.log("Error getting document: ", error);
                });

                // outputData();

                db.collection("students").get().then(function(querySnapshot) {
                    querySnapshot.forEach(function(doc) {
                        // doc.data() is never undefined for query doc snapshots
                        console.log(doc.id, " => ", doc.data());

                });
                    })
                    .catch(function(error) {
                        console.log("Error getting documents: ", error);
            });

        }) //close submit form click function


//close document read function              
    });

我希望该表显示已添加的新文档

但是,数据库中的所有数据都追加到当前数据的底部,我只希望新文档显示在页面中,最好按学生的姓氏顺序显示。

更新

使用弗兰克·范·普菲伦(Frank van Puffelen)的回复,我已经解决了

我创建了一个新的html变量,里面有一个空白的div 然后,我使用.add为先前编写的for循环的每次迭代添加代码。

然后,我使用.html调用变量html并更新页面代码。

db.collection("students").onSnapshot(function(querySnapshot) {


                        let html = $("<div></div>");

                        querySnapshot.forEach(function(doc) {

                            let student = doc.data();



                            html = html.add($('<tr> \
                                        <th scope="row">'+doc.id+'</th> \
                                         <td>'+student.first_name+'</td> \
                                         <td>'+student.last_name+'</td> \
...
$('#overallDashboard > tbody:last-child').html(html);

1 个答案:

答案 0 :(得分:0)

您有这段代码可监听数据库中的数据和更改:

db.collection("students").onSnapshot(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        let student = doc.data();

        $('#overallDashboard > tbody:last-child').append(
            ...

请记住,onSnapshot会被集合中的所有数据调用。因此,当您首次连接到Firestore时,以及每当数据更改时,您都会从students获取所有文档,然后将它们添加#overallDashboard。这意味着您第一次遇到所有学生。假设有3个学生,您最终得到一张桌子,上面有:

student 1
student 2
student 3

现在,当有更改时,您可以将完整的数据添加到表的末尾。因此,您最终获得了原始内容。假设您要添加其他学生文档,则最终得到:

student 1 // first time onSnapshot got called
student 2
student 3
student 1 // second time onSnapshot got called
student 2
student 3
student 4

然后例如当您删除第一个学生时,您最终得到:

student 1 // first time onSnapshot got called
student 2
student 3
student 1 // second time onSnapshot got called
student 2
student 3
student 4
student 2 // third time onSnapshot got called
student 3
student 4

有两种解决方法:

  1. 每次调用onSnapshot时都要清除表。

  2. 确定对数据进行的确切更改,然后更新该HTML。

虽然第二种方法更有效,但也涉及更多点。因此,我将在下面显示一种简单的方法,该方法是每次调用onSnapshot时清除表中的HTML:

db.collection("students").onSnapshot(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        let student = doc.data();

        $('#overallDashboard > tbody:last-child').html(
            ...