最终更新我从使用基于 andresmijares 的以下答案的事务更改为使用 set()。
现在我可以将数据写入数据库。
var gradeDocRef = db.collection("students").doc(studentId);
console.log(gradeDocRef);
var setWithMerge = gradeDocRef.set({
"UnitGrades": {
[unitNo]: {
"CG": CG,
"PG": PG,
"TG": TG
}
}
}, { merge: true });
Edit我根据下面 andresmijares 的评论更改了交易代码。
transaction.set(gradeDocRef, {merge: true}, {
但然后得到这个错误?
未知选项“UnitGrades”传递给函数 Transaction.set()。可用选项:合并、mergeFields
我有一个包含学生集合的云 Firestore 数据库。
每个学生集合都包含一个学生文档,其中包含地图和子地图,如下所示
UnitGrades:
{
IT1:
{
CG: "F"
PG: "F"
TG: "F"
id: "IT1"
name: "Fundamentals of IT"
type: "Exam"
}
我在地图中有 10 个单位 UnitGrades
每个学生都有相同的单元组合
我想根据 bootstrap 中的 HTML 表单更新地图(该表单正在工作,而且很长,所以不要把它放在这里)
即更改学生成绩
我使用了 firestore 事务更新文档,并稍加修改以从 HTML 表单中获取数据。
let studentId = $(this).attr("data-student-id");
let unitNo = $(this).attr("data-unit");
let CG = $(this).attr("data-CG");
let PG = $(this).attr("data-PG");
let TG = $(this).attr("data-TG");
// Create a reference to the student doc.
var gradeDocRef = db.collection("students").doc(studentId);
console.log(gradeDocRef);
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(gradeDocRef).then(function(gradeDoc) {
if (!gradeDoc.exists) {
throw "Document does not exist!";
}
// update the grades using a transaction
transaction.update(gradeDocRef, {
// in here is my error, I need to be able to select the map
// for the variable for UnitNo only and not wipe the other maps
"UnitGrades": {
[unitNo]: {
"CG": CG,
"PG": PG,
"TG": TG }
});
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
console.log(studentId);
});
我实现的代码更新了正确的单位映射,但随后擦除了其余的单位等级。我真正想要的是更新变量中标识的单位映射
UnitNo
然后保持其余单元不变。
例如目前,如果我更新 IT1,这会正确更新地图内的成绩,但随后会从 UnitGrades 地图中擦除单位 IT2、IT3、IT12 等。我真的希望 IT2、IT3、IT12 等保持不变,而 IT1 使用新值进行更新。例如“F”更改为“P”