首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Firestore云文档中对象和键的动态更新

Firestore云文档中对象和键的动态更新
EN

Stack Overflow用户
提问于 2019-08-16 21:14:25
回答 1查看 268关注 0票数 0

我正在更新一个包含多个对象的firestore文档。下面是文档结构:

代码语言:javascript
复制
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,
}

我可以手动更新特定值,如下所示:

代码语言:javascript
复制
2019.2: admin.firestore.FieldValue.increment(1) //changing the value of March 2019

我不能动态地改变它。我试着这样做:

代码语言:javascript
复制
var year = new Date().getFullYear().toString()
var month = new Date().getMonth().toString()


[year].[month]: admin.firestore.FieldValue.increment(1)

我尝试使用[]s和s,但它们都不起作用。下面是完整的函数:

代码语言:javascript
复制
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'));

});

有没有什么方法可以让我同时动态访问对象和它的键。

EN

回答 1

Stack Overflow用户

发布于 2019-11-27 21:49:24

要解决这个问题,首先用您期望的最终值创建一个变量,然后按如下所示进行赋值:

代码语言:javascript
复制
{[variable]: admin.firestore.FieldValue.increment (1)}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57525335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档