首页 > 解决方案 > 在 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'));

});

有什么方法可以访问该对象,并且同时动态地访问它。

标签: javascriptobjectgoogle-cloud-firestore

解决方案


为了解决这个问题,首先创建一个具有您期望的最终值的变量,然后按如下方式分配它:

{[variable]: admin.firestore.FieldValue.increment (1)}

这样,您将不会传递文字字符串,而是将变量的值作为对象的键。


推荐阅读