首页 > 解决方案 > Angular 6 和 AngularFirestore 插入、更新

问题描述

在下面的代码中,我拥有的是按钮事件处理程序,当调用它时会获取一个 questionId 和一个 userId。然后它检查 Answers 集合以查看该用户是否已经回答了给定的问题。如果是,请进行更新,如果不是,请进行插入。这段代码几乎可以工作。当我更新时,它会导致无限循环?!我不确定为什么?想法?

addAnswer(answer: string) {

var questionId = this.selectedQuestion.id;
var userId = this.selectedUser.id;
//FIRST: check to see if this user already answered this question
// if so, do an update, not an add
var answersRef = this.db.collection('Answers', ref => {
    // Compose a query using multiple .where() methods
    return ref
        .where('userId', '==', userId)
        .where('questionId', '==', questionId)
});


answersRef.snapshotChanges().subscribe(
    data => {
        console.log(data);
        //
        if (data.length > 0) {
            //UPDATE as they already have an answer to the question
            console.log('UPDATE');
            data.map( a => {
                console.log(a.payload.doc.id);
                //
                this.db.collection('Answers').doc(a.payload.doc.id).update({
                    answer: answer,
                    date: null,
                    isPublic: true,
                    //questionId: questionId,
                    //userId: userId,
                })
                .then( docRef => {
                    console.log("Document successfully updated!");

                }) 
                .catch( error => {
                    console.error("Error adding document: ", error);
                });
            });
        }
        else {
            //INSERT
            console.log('INSERT');
            this.db.collection('Answers').add({
                answer: answer,
                date: null,
                isPublic: true,
                questionId: questionId,
                userId: userId,
              })
              .then( docRef => {
                console.log("Document written with ID: ", docRef.id);
              })
              .catch( error => {
                console.error("Error adding document: ", error);
              });
        }

    }
);

}

标签: angularfirebaseangularfire

解决方案


推荐阅读