node.js - 如何使用 Firebase 管理 sdk 更新 Firestore 中的用户列表?

标签 node.js firebase google-cloud-firestore firebase-admin

所以我正在学习如何使用 firebase admin sdk,并且遇到了一个我不够理解无法解决的问题。基本上,我已经查询了我的数据库并获得了我想用相同值更新的用户子集。因此,我将要更新的每个用户的 id 存储在一个数组中,现在我尝试循环该数组并更新每个用户。但我在实现这部分时遇到了问题,这与 .update() 返回一个 promise 有关,而我并不是 100% 如何在循环中处理这个问题...

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp()
exports.getAllUsers = functions.https.onRequest((request, response) => {
  const db = admin.firestore()
  const users = db.collection('users').where('role', '==', 'artist').get()
    .then(function (querySnapshot) {
      //const users = querySnapshot.data()
      const promises = []
      querySnapshot.forEach(function (doc){
        promises.push(doc)
      })
      return Promise.all(promises) //returning promises sends the resolved results to 
    })                             //to the next .then()
    .then(function (person){
      let results = []
      person.forEach(function(personSnap){
        //const data = personSnap.data()
        results.push(personSnap.id)
      })
      return results  // results is the array of ids to update
    })
    //This .then() is where I have trouble understanding how to update
    .then(function (ids){
      for(var i = 0; i<ids.length; i++){
        var artistsRef = db.collection('users').doc(ids[i]);

        artistsRef.update({ //Should not be a return statement. This fixed my problem. Otherwise it would update the first user in the array and then leave the for loop.
          'free_credits': '2'
        })
      }
      return 'finished'
    })
    .then(function(reply) {
      return response.send(reply)
    })
    .catch(function (error){
      response.send(error)
    })

})

我觉得我应该返回“artistsRef.update()”,因为它是一个 promise ,但我认为这会导致意想不到的结果。

如果我不返回 update(),那么 ESLint 会抛出错误:“每个 then() 应该返回一个值或抛出”

最佳答案

在发送响应之前,您将在最终 then() 回调中提前返回。也许您应该添加另一个 then() 只是为了在最终更新完成后发送结果。

关于node.js - 如何使用 Firebase 管理 sdk 更新 Firestore 中的用户列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524196/

相关文章:

java - 关闭时使用 Firebase 保持应用登录状态

flutter - Firestore 不存储来自 TextField 的新行

php - express 返回无法 GET/home

node.js - Express.js - req.query 与 req.params

node.js - nodejs mongodb对象ID到字符串

google-cloud-firestore - 如何处理 Firestore 安全规则中的 FieldValue.delete()?

firebase - 用RxDart在dart-flutter中进行Concanete 2 Firestore QuerySnapShot流

javascript - 在 Javascript 中将多个 Promise 插入数组时处理单个错误

javascript - FIREBASE - 引用错误 : Cannot access 'auth' before initialization

ios - 将字典发送到核心数据