0

I am building a chatbot on Dialogflow and using Firestore as my database. I was originally using a custom auto ID generator, but I am now trying to use Firestores in built one, and getting errors with my current code.

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.`);
  });
}

I have changed the important lines to:

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

Which does successfully write to the db and auto generates an ID. Although an error is being caught:

Argument "documentRef" is not a valid DocumentReference. Input is not a plain JavaScript object

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Willumosa
  • 11
  • 2

1 Answers1

0

This makes no sense:

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

In this line the db.collection("WaterConsumption").add(databaseEntry) is a call to Firestore to create a document outside of the transaction). What you want instead is to just create a new DocumentReference with a unique ID, which (as shown in the 3rd snippet in the documentation on adding documents) can be done with doc().

So:

const newDocRef = db.collection("WaterConsumption").doc();
t.set(newDocRef, databaseEntry);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807