angular - 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);
});
}
}
);
}
解决方案
推荐阅读
- python - 有选择地删除熊猫数据框 NaN 行,按包含重复项的 id 列分组
- flutter - VS Code Wrap with Widget Auto Suggestion 建议参数/参数
- python - Matplotlib 获取 z 数据
- tensorflow - 有没有办法在我自己的环境中应用 tensorflow dqn?最终通过 api 接口
- arrays - 如何防止用户输入破坏堆栈?
- c - va_arg 如何在可变参数函数中实际工作?
- testing - 使用安全帽通过 Uniswap 流动性供应测试代币
- php - 它创建了一条记录,但它是空的
- javascript - 反应导航错误```无法确定任务':app:collectReleaseDependencies'的依赖关系'
- database - 将 API 连接到数据库