簡體   English   中英

如何在不指定文檔 ID 和使用 Firestore 自動 ID 生成器的情況下添加到 Firestore?

[英]How can I add to Firestore without specifying a document ID and utilising Firestores auto ID generator?

我正在 Dialogflow 上構建一個聊天機器人,並使用 Firestore 作為我的數據庫。 我最初使用的是自定義自動 ID 生成器,但我現在嘗試在內置的 Firestore 中使用,並且當前代碼出現錯誤。

function AddWaterConsumption (agent) {
  // Get parameter from Dialogflow with the string to add to the database
  var databaseEntry = { 
      "PatientID": agent.parameters.Patient_ID,
      "DailyConsumption": agent.parameters.Water_consumption_user,
      "DailyWaterPlan": agent.parameters.Daily_water_plan,
  };
  let Patient_ID = agent.parameters.Patient_ID;
  console.log(`Okay, we're trying to write to database: ${databaseEntry}`);
  
  // here is where changes are needed
  const dialogflowAgentRef = db.collection("WaterConsumption").doc(genRand(8)); // need to change to add()    
  console.log(`Found agent ref: ${dialogflowAgentRef}`);
  return db.runTransaction(t => {
    t.set(dialogflowAgentRef, databaseEntry); // this will also need to be changed
    return Promise.resolve('Write complete');
 
  }).then(doc => {
    agent.add(`I have updated your daily water consumption`); 
    agent.add(`Is anything else I can do for you?.`);
  }).catch(err => {
    console.log(`Error writing to Firestore: ${err}`);
    agent.add(`Failed to write "${dialogflowAgentRef}" to the Firestore database.`);
  });
}

我已將重要的行更改為:

console.log(`Okay, we're trying to write to database: ${databaseEntry}`);
const dialogflowAgentRef = db.collection("WaterConsumption"); // changed here
console.log(`Found agent ref: ${dialogflowAgentRef}`);
return db.runTransaction(t => {
  t.set(db.collection("WaterConsumption").add(databaseEntry), databaseEntry); // and here

它確實成功寫入數據庫並自動生成一個 ID。 雖然正在捕獲錯誤:

參數“documentRef”不是有效的 DocumentReference。 輸入不是普通的 JavaScript object

這沒有任何意義:

t.set(db.collection("WaterConsumption").add(databaseEntry), databaseEntry);

在這一行中, db.collection("WaterConsumption").add(databaseEntry)是對 Firestore 的調用,以在事務之外創建文檔)。 相反,您想要創建一個具有唯一 ID 的新DocumentReference ,這可以使用doc()完成(如添加文檔文檔中的第三個片段所示)。

所以:

const newDocRef = db.collection("WaterConsumption").doc();
t.set(newDocRef, databaseEntry);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM