how to integrate MongoDB database with dialogfow

旧时模样 提交于 2019-12-02 04:40:44

Follow the steps to connect MongoDB ( using Mongoose )to your Dialogflow. I am continuing with the code you provided.

Code

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const mongoose = require('mongoose');

// you can use your mongodb connection url string
let uri = 'mongodb://sairaj:pasword@ds239071.mlab.com:39071/pictassistant';

let Song; 

mongoose.connect(uri,{ useNewUrlParser: true });

let mdb = mongoose.connection;

mdb.on('error', console.error.bind(console, 'connection error:'));

mdb.once('open', function callback() {

  // Create song schema
  let songSchema = mongoose.Schema({
    decade: String,
    artist: String,
    song: String,
    weeksAtOne: Number
  });

  // Store song documents in a collection called "songs"
  // this is important ie defining the model based on above schema
  Song = mongoose.model('songs', songSchema);  

  // Create seed data
  let seventies = new Song({
    decade: '1970s',
    artist: 'Debby Boone',
    song: 'You Light Up My Life',
    weeksAtOne: 10
  });

//use the code below to save the above document in the database!
/*   seventies.save(function (err) {

            console.log('saved');

     });
*/

 });

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {

// I use the code below to find a song from databse and ask the user whether he wants to listen to it 
// Use the code below to extract data based on your criteria
    return Song.find({ 'song': 'You Light Up My Life' }, 'song')
      .then((songs) => {

            //songs is araay matching criteria, see log output
            console.log(songs[0].song); 
            agent.add(`Welcome to my agent! Would you like to listen ${songs[0].song}?`);

      })
      .catch((err) => {

           agent.add(`Therz some problem`);

      });

  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}


  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome); 
  intentMap.set('Default Fallback Intent', fallback);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

Firebase Logs

Google Assistant Output

Notes:

  1. If your MongoDB database is hosted on an external network, it is necessary to use a Billing Firebase Account (Very Important)
  2. Refer Mongoose Docs for more functions like update and delete operations.
  3. You don't necessarily need a MVC Structure to connect MongoDB to Dialogflow.
  4. Make sure you add mongoose in package.json by running npm install mongoose --save in your functions folder. This would solve problems such as Cannot find module mongoose.

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!