如何在Firebase Cloud功能中更新文档 [英] How to update document in firebase cloud function

查看:52
本文介绍了如何在Firebase Cloud功能中更新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的云功能中,当新学生添加到学生"集合中时,我想从仪表盘"集合中更新文档.

In my cloud function I want to update my document from 'dashboard' collection when a new student added to 'students' collection.

const getActiveStudents = () => {
return db.collection('/students/').where('status', '==', true).get().then(
    snapshot => {
        let studentsCount = snapshot.docs.length;
        db.collection('/dashboard/').where('type', '==', 'students').get().then(
            result => {
                if (result.docs.length === 0) {
                    db.collection('dashboard').add({
                        count: studentsCount,
                        type: 'students',
                        label: 'Active students'
                    });
                }else {
                    result.docs[0].ref.update({
                        count: studentsCount,
                        type: 'students',
                        label: 'Active students'
                    });
                }
                return result;
            }
        ).catch(error => {
            console.log(error);
        });
        return snapshot;
    }
).catch(error => {
    console.log(error);
})
}

exports.onChangesInStudents = functions.firestore.document('/students/{studentId}').onWrite(event => {
    getActiveStudents();
    return;
});

当我添加一个新学生时,不是更新文档,而是将一个新文档添加到我的仪表盘"集合中.我应该如何组织我的代码,以便正确地更新学生数量.

When I add a new student, instead of updating document it adds a new document to my 'dashboard' collection. How should I organize my code in order to properly update the quantity of students.

推荐答案

,遍历整个集合太繁琐了.相反,您可以使用 query.stream().

as @Doug mentioned, iterating over the entire collection is too heavy. instead you can stream the query results and iterate over keys, using query.stream().

要访问和更新文档中的单个字段,请首先使用

to access and update a single field in a document, first retrieve the document by its ID with doc(), then use update() while specifying the field.

这是根据您的情况实现的示例.

here's an example of implementation based on your scenario.

package.json

{
  "dependencies": {
    "firebase-admin": "^6.5.1",
    "firebase-functions": "^2.1.0"
  }
}

index.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

const studentsRef = admin.firestore().collection('students');
const dashboardRef = admin.firestore().collection('dashboard');

exports.addStudent = functions.firestore
  .document('students/{studentId}')
  .onCreate((snap, context) => {
    var newStudent = snap.data();
    console.log('New student in collection: ', newStudent);

    var activeCount = 0;
    studentsRef.where('status', '==', true).select().stream()
      .on('data', () => {
        ++activeCount;     
      }).on('end', () => { 
        dashboardRef.where('type', '==', 'students').get()
          .then(querySnap => {
            if (querySnap.docs[0].data().count == activeCount){
              console.log('No new active student: ', querySnap.docs[0].data());
            } else {
                console.log('New active count: ', activeCount);
                console.log('Student Dashboard before update: ', querySnap.docs[0].id, '=>', querySnap.docs[0].data());
                dashboardRef.doc(querySnap.docs[0].id).update({
                  count: activeCount
                });
                console.log('Active student count updated: ', querySnap.docs[0].data().count, '=>', activeCount);
              };
            });
        });
  return null
  });

gcloud

gcloud functions deploy addStudent \
  --runtime nodejs8 \
  --trigger-event providers/cloud.firestore/eventTypes/document.create \
  --trigger-resource "projects/[PROJECT_ID]/databases/(default)/documents/students/{studentId}"

这篇关于如何在Firebase Cloud功能中更新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆