How to fetch an array of map from snap on DialogFlow fullfilment using Firestore

234 views Asked by At

I've written into an array from input data on Dialogflow using Firestore, like this.

But I don’t know how to fetch data from Firestore to display in Dialogflow, and there's my programming below it.

Here is what I want to achieve. When I input number in Dialogflow, I would like to get an array of number from the Firestore instance.

const db = admin.firestore();
db.settings({timestampsInSnapshots: true}); 
.
.
.
const sessionId = request.body.session.split("/").reverse()[0]; // or agent.session

  function read(agent){
    const number = agent.parameters.number;  // when I input the number in Fialogflow
    const docRef = db.collection('orders').doc(sessionId);

    return docRef.get()
      .then(doc => {
        if (!doc.exists) {
          agent.add('No data found in the database!');
          console.log(doc);
        } else {
          agent.add(doc.data().orders);
        }
        return Promise.resolve('Read complete');
      }).catch(() => {
        agent.add('Error reading entry from the Firestore database.');
        agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
      });
  }

  function writeOrderToDb (newOrder) {
    const docRef = db.collection('orders').doc(sessionId);

    return db.runTransaction(t => {
      return t.get(docRef)
      .then(doc => {
        t.update(docRef, {
          orders: admin.firestore.FieldValue.arrayUnion(newOrder)
        }, {merge: true});
        /*if (!doc.data()) {
          t.set(docRef, { orders: [newOrder] });
        }
        else {
          t.update(docRef, {
            orders: admin.firestore.FieldValue.arrayUnion(newOrder)
          });
        }*/
      });
    }).catch(err => {
      console.log(`Error writing to Firestore: ${err}`);
    });
  }


  function confirmOrder(agent) {
    const order = agent.context.get('order'),
          amount = order.parameters.amount,
          size = order.parameters.size,
          type = order.parameters.type;

    agent.add(`Confirming ${amount} ${type} in ${size}`);

    // important to return, otherwise console.logs will not appear and non-deterministic behavior will ocurr
    return writeOrderToDb({
      "type": type,
      "size": size,
      "amount": amount
    });
  }
1

There are 1 answers

3
Waelmas On

I have created the same data model as yours:

enter image description here

So with the following code, you can pass any number within the range of your array "orders" into the variable my_num. It will return the data inside that part of the array.

var my_num = 1;

db.collection('dial').doc('dial1').get().then(function(doc) {
  console.log(doc.data().orders[my_num]);
});

Output:

enter image description here