javascript - 在 Firestore 云文档中动态更新对象和键
问题描述
我正在更新包含多个对象的 Firestore 文档。这是文档结构:
2019: { // each key is month and value is number of projects submitted each month
0: 12,
1: 15,
2: 5,
3: 5,
4: 200,
5: 15,
6: 12,
7: 15,
8: 215,
9: 15,
10: 12,
11: 15,
},
2020: {
0: 3,
1: 100,
2: 5,
3: 75,
4: 200,
5: 15,
6: 12,
7: 15,
8: 215,
9: 15,
10: 13,
11: 200,
}
我可以像这样手动更新特定值:
2019.2: admin.firestore.FieldValue.increment(1) //changing the value of March 2019
我无法动态更改它。我正在尝试这个:
var year = new Date().getFullYear().toString()
var month = new Date().getMonth().toString()
[year].[month]: admin.firestore.FieldValue.increment(1)
我尝试使用 []s 和 ``s 但它们不起作用。这是完整的功能:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.projectAdded = functions.firestore.document('projects/{projectId}').onCreate(doc => {
const project = doc.data();
// Get a new write batch
var batch = admin.firestore().batch();
// Update count of 'all' Category doc in categories
var allCat = admin.firestore().collection("categories").doc("all");
batch.update(allCat, {
All: admin.firestore.FieldValue.increment(1),
[project.category]: admin.firestore.FieldValue.increment(1)
});
// Update count of 'user Category' doc in categories
var userCat = admin.firestore().collection("categories").doc(project.authorId);
batch.update(userCat, {
All: admin.firestore.FieldValue.increment(1),
[project.category]: admin.firestore.FieldValue.increment(1)
});
// Update count of 'user projects' doc in Users
var userQ = admin.firestore().collection("users").doc(project.authorId);
var year = new Date().getFullYear().toString()
var month = new Date().getMonth().toString()
batch.update(userQ, {
projectsAdded: admin.firestore.FieldValue.increment(1),
[year]: admin.firestore.FieldValue.increment(1),
`${year}.${month}`: admin.firestore.FieldValue.increment(1),
});
return batch.commit().then(function () {
console.log("Adding categories")
})
.then(doc => console.log('Categories Added'));
});
有什么方法可以访问该对象,并且同时动态地访问它。
解决方案
为了解决这个问题,首先创建一个具有您期望的最终值的变量,然后按如下方式分配它:
{[variable]: admin.firestore.FieldValue.increment (1)}
这样,您将不会传递文字字符串,而是将变量的值作为对象的键。
推荐阅读
- iterator - 如何通过小数据集进行采样以进行比数据大小更多的迭代?
- apache-spark-sql - 如何使用 Spark 中的 scala 将 RDD[DataFrame] 中的所有 DataFrame 合并到 DataFrame 而不使用 for 循环?
- python-3.x - ImportError:没有名为 xlrd 的模块
- python - django单页上的两部分表单
- java - 嵌套 if 或 code 多次?
- javascript - 使用 kallyas-child 主题的 WordPress 错误
- git - Git 将 'origin/5.4' 重命名为 'origin/5.5'
- pycharm - 如何设置 PyTorch 共享内存大小?
- datepicker - VueJs - el-date-picker:如何设置格式默认值 new Date()
- joomla - Joomla 管理员使用自定义默认组父添加新组