我正在更新包含多个对象的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,但它们不起作用。这是全部功能:
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'));
});
有什么方法可以同时动态访问对象及其密钥。
答案 0 :(得分:0)
要解决该问题,请首先创建一个最终值与您期望的值相同的变量,然后按如下所示对其进行分配:
{[variable]: admin.firestore.FieldValue.increment (1)}
那样,您将不会传递文字字符串,而是将变量的值作为对象的键。