我正在更新一个包含多个对象的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'));
});有没有什么方法可以让我同时动态访问对象和它的键。
发布于 2019-11-27 21:49:24
要解决这个问题,首先用您期望的最终值创建一个变量,然后按如下所示进行赋值:
{[variable]: admin.firestore.FieldValue.increment (1)}这样,您将不会传递文字字符串,而是传递变量的值作为对象的键。
https://stackoverflow.com/questions/57525335
复制相似问题