【发布时间】:2019-10-23 16:43:52
【问题描述】:
最终更新 我从使用基于 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 });
编辑 我根据下面 andresmijares 的评论更改了交易代码。
transaction.set(gradeDocRef, {merge: true}, {
然后得到这个错误?
传递给函数 Transaction.set() 的未知选项“UnitGrades”。可用选项:合并、合并字段
我有一个包含学生集合的云 Firestore 数据库。 每个学生集合都包含一个学生文档,其中包含如下图和子图
UnitGrades:
{
IT1:
{
CG: "F"
PG: "F"
TG: "F"
id: "IT1"
name: "Fundamentals of IT"
type: "Exam"
}
我在地图 UnitGrades 中有 10 个单位 每个学生都有相同的单元组合
我想在 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);
});
我实现的代码更新了正确的单元映射,但随后擦除了 UnitGrades 的其余部分。我真正想要的是更新变量中标识的单位映射
UnitNo,然后保持其余单元不变。
例如目前,如果我更新 IT1,这会正确更新地图中的等级,但随后会从 UnitGrades 地图中擦除单位 IT2、IT3、IT12 等。我真的希望 IT2、IT3、IT12 等保持原样,并使用新值更新 IT1。例如“F”变为“P”
【问题讨论】:
-
代替更新,使用 set 并传递 { merge: true } 作为第二个参数
-
@andresmijares 我已经尝试过了,编辑了上面的原始问题以显示我现在得到的错误?
-
看来你有参数错误,让我写一个答案给你检查,我的意思是参考后的第二个参数^^对不起
标签: javascript firebase google-cloud-firestore