Firestore数据库中的云功能更新问题

时间:2019-03-13 21:38:08

标签: firebase google-cloud-firestore google-cloud-functions

我正在尝试构建一个Android应用程序。在我的Firestore数据库中,有“用户”集合和“计数器”集合。在Counters集合中,我有userCounter。我想做的是每当有新用户登录并将其推送到firestore时,userCounter都会增加。

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

exports.addNewUser = 
functions.firestore.document('Users/{userID}').onCreate((event) => {

var db = admin.firestore();
var counterRef = db.collection("Counters");
var temp = counterRef.doc("0").data().userCounter++;

counterRef.doc("0").update(
{
    userCounter: temp
});
});

在这种状态下,此功能不起作用,我是新手,因此,我们将不胜感激。 事先谢谢

编辑

实现Firebaser和PabloAlmécijaRodríguez的答案后,我的代码如下所示。

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore({
  projectId: process.env.GCP_PROJECT,
});
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.addNewUser =
functions.firestore.document('Users/{userId}').onCreate((snapShot) => {

  const userCounterRef = db.collection('Counters').doc('Users');

  return db.runTransaction(transaction => {

   const doc = transaction.get(userCounterRef);

    console.log("1");
   const count = doc.data();
    console.log(`5`);
   const updatedCount = count + 1;
    console.log(`6`);
   return transaction.update(userCounterRef, {counter: updatedCount })
  })
});

这是Firebase控制台日志。问题是

const count = doc.data();
TypeError: doc.data is not a function

Firebase Console Log

2 个答案:

答案 0 :(得分:0)

我建议您创建一个名为counters的集合,并在其中创建一个名为users的文档以为用户处理counter。这是结构:

- counters (collection)
  - users (document)
    count: 0 (field)

然后,您应该使用交易记录对该计数器文档进行更新,以确保您正在使用最新数据来处理并发(同时创建多个帐户)

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.addNewUser = 
functions.firestore.document('users/{userId}').onCreate((snapShot) => {

  const userCounterRef = db.doc('counters/users');

  return db.runTransaction(async transaction => {
   const doc = await transaction.get(userCounterRef)
   const { count } = doc.data()
   const updatedCount = count + 1
   return transaction.update(userCounterRef, {count: updatedCount })
  })
});

https://firebase.google.com/docs/firestore/manage-data/transactions

编辑:如果您不想使用异步/等待语法,请像这样更新您的事务:

return db.runTransaction(transaction => {
     return transaction.get(userCounterRef)
     .then(doc => {
         const count = doc.data().count
         const updatedCount = count + 1
         transaction.update(userCounterRef, {count: updatedCount })
     })

})

答案 1 :(得分:0)

我已经在Cloud Functions中复制了它,并且这个简单的解决方案起作用了。 已编辑答案以适合Firebase,并且它也将Firestore dependency用于nodejs。

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore({
  projectId: process.env.GCP_PROJECT,
});

const functions = require('firebase-functions');
//I am not using next two lines right now though
const admin = require('firebase-admin');
admin.initializeApp();

exports.helloFirestore = 
functions.firestore.document('users/{userID}').onCreate((event) => {


  const doc = firestore.doc('Counters/UserCounter/');
  doc.get().then(docSnap => {
    //Get the specific field you want to modify
    return docSnap.get('userCount');
  }).then(field => {
    field++;
    //Log entry to see the change happened
    console.log(`Retrieved field value after +1: ${field}`);
    //Update field of doc with the new value
    doc.update({
      userCount: field,
    });
  });
});

您使用的通配符应该很好,请注意收集的完整路径,请注意大小写。对于这种情况,这就是我的 package.json 的样子:

{
  "name": "sample-firestore",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/firestore": "^1.1.0",
    "firebase-functions": "2.2.0",
    "firebase-admin": "7.0.0"
  }
}