【问题标题】:PROBLEM Getting a single field in a document in Firebase Firestore问题在 Firebase Firestore 的文档中获取单个字段
【发布时间】:2019-03-10 21:43:35
【问题描述】:

我正在尝试在 Firebase 中执行云功能。最初,我阅读了我的文档。然后我会从这个文档中获取两个字段“a”和“b”。然后我想将我的文档的另一个字段('rank')设置为'a'和'b'的总和。我找不到解决办法! 我只想从我的文档中获取字段“a”和“b”。将它们保存在变量中。并使用这些变量进行求和,并将结果设置在“排名”字段中。

我试过了:

var data = doc.data()
a = data.a
b = data.b

但它不起作用。

代码:

export const daicazzo = functions.https.onRequest((request,response)=>{

  const store = admin.firestore();

  //var b;
  store.collection('questions').doc('LD92BBDOihAC3fHDyoV').get().then(doc =>{
    if(doc.exists){
      response.send(doc.data())
    }
    else{
      response.send("Nothing")
    }
  }).catch(reason => {
    console.log(reason)
    response.send(reason)
  })

  store.collection('questions').doc('LD92BBDOihAC3fHDyoV').set({
    rank: //a+b
    })
    .then(function() {
      console.log("done");
})
.catch(function(error){
  console.log("Error:",error);
});
});

【问题讨论】:

  • 您必须将新值写回文档。它不会自己写。
  • 将图像中的代码粘贴到问题中,以便有人可以检查问题。
  • @Fire-In-D-Hole 或“粘贴”它。
  • @DougStevenson 为粘贴代码的错字道歉。

标签: firebase google-cloud-firestore


【解决方案1】:

应该做的工作(可能是一些更好的解决方案)

const store = admin.firestore();

export const daicazzo = functions.https.onRequest(async (request,response)=>{
   const questionRef = store.doc(`questions/${LD92BBDOihAC3fHDyoV}`)
   const doc = await questionRef.get()
   const foundDoc = doc.exists

   if (foundDoc) {
     // getting both key/value pairs from doc object
     const {a, b} = doc.data()

     const rank = a + b // whatever is your logic...

     // saving the rank in the same document
     await questionRef.update({rank}) // or questionRef.set({rank}, {merge: true})

     if you want to send back the doc with the updated rank without making another read, assuming you handle errors:
     const { id } = doc
     const updatedDoc = { ...doc.data(), id, rank }
     return response.send(updatedDoc)
   } else {
     return response.send("Nothing")
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2021-06-24
    • 2018-06-16
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多