如何将MongoDB数据库与dialogfow集成 [英] how to integrate MongoDB database with dialogfow

查看:69
本文介绍了如何将MongoDB数据库与dialogfow集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Webhook应用程序,已从Firebase数据库成功检索了数据。但是我需要合并MongoDB。

 使用严格; 

const函数= require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const mongoose = require(‘mongoose’);
process.env.DEBUG =‘dialogflow:debug’; //启用lib调试语句


let uri ='mongodb:// dbAdynor:Adynor123!@ testcluster-shard-00-00-x87dz.gcp.mongodb.net:27017,testcluster -shard-00-01-x87dz.gcp.mongodb.net:27017,testcluster-shard-00-02-x87dz.gcp.mongodb.net:27017/test?ssl=true&replicaSet=TestCluster-shard-0&authSource = admin& retryWrites = true';
让db;

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

让mdb = mongoose.connection;
mdb.on(错误,console.error.bind(控制台,连接错误:));

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

//创建歌曲模式
让dbSchema = mongoose.Schema({
十年:弦乐,
艺术家:弦乐,
歌曲:弦乐,
weekAtOne:数字
});
db = mongoose.model('songs',dbSchema) ;

让入场券=新数据库({
十年:'1970s',
艺术家:'Debby Boone',
首歌:'You Light Up My Life' ,
weekAtOne:10
});
});
exports.dialogflowFirebaseFulfillment =函数.https.onRequest((请求,响应)=> {
const agent = new WebhookClient({request,response});
console.log('Dialogflow请求标头:'+ JSON.stringify(request.headers));
console.log('Dialogflow请求正文:'+ JSON.stringify(request.body));
console.log( request .body.queryResult.parameters:,request.body.queryResult.parameters);
var params = request.body.queryResult.parameters;
// var name = request.body.queryResult.parameters [ 'myName'];


var intentMap = new Map();
// intentMap.set('Default Welcome Intent',welcome);
// intentMap.set('Default Fallback Intent',fallback);

agent.handleRequest(intentMap);

});

我收到一个错误消息:您是否在package.json依赖项中列出了所有必需的模块?

 详细的堆栈跟踪:错误:在Function.Module._resolveFilename(module.js上找不到模块'猫鼬'
:476:15)Function.Module._load(module.js:424:25)
在Module.require(module.js:504:17)
在require(内部/ module.js:20:19)
在Object。< anonymous>(/user_code/index.js:5:18)
在Module._compile(module.js:577:32)
在Object.Module._extensions..js(module.js:586:10)
在Module.load(module.js:494:32)
在tryModuleLoad(module.js:453: 12)Function.Module._load上的
(module.js:445:3)



有什么办法解决吗?

解决方案

连接MongoDB的步骤(使用



Google Assistant输出





注意:


  1. 如果您的MongoDB数据库托管在外部网络上,则需要
    使用结算Firebase
    帐户

    (非常重要)

  2. 请参阅猫鼬文件可获得更多功能,例如更新和删除操作。

  3. 您不一定需要MVC结构至

  4. 确保通过运行 npm install mongoose --save package.json 中添加猫鼬。 $ c>在您的函数文件夹中。这样可以解决诸如找不到模块猫鼬之类的问题。

希望有帮助!


I have a webhook application where I have successfully retrieved data from Firebase database. But I need to incorporate MongoDB instead. This is the code so far.

  'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const mongoose = require('mongoose');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements


let uri = 'mongodb://dbAdynor:Adynor123!@testcluster-shard-00-00-x87dz.gcp.mongodb.net:27017,testcluster-shard-00-01-x87dz.gcp.mongodb.net:27017,testcluster-shard-00-02-x87dz.gcp.mongodb.net:27017/test?ssl=true&replicaSet=TestCluster-shard-0&authSource=admin&retryWrites=true';
let db;

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

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

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

  // Create song schema
  let dbSchema = mongoose.Schema({
    decade: String,
    artist: String,
    song: String,
    weeksAtOne: Number
  });
db=mongoose.model('songs',dbSchema);

let admission = new db({
    decade: '1970s',
    artist: 'Debby Boone',
    song: 'You Light Up My Life',
    weeksAtOne: 10
  });
});
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));
  console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
  var params = request.body.queryResult.parameters;
//  var name = request.body.queryResult.parameters['myName'];


   var intentMap = new Map();
 // intentMap.set('Default Welcome Intent', welcome);
 // intentMap.set('Default Fallback Intent', fallback);

  agent.handleRequest(intentMap);

});

I am getting an error that says "Did you list all required modules in the package.json dependencies?

Detailed stack trace: Error: Cannot find module 'mongoose'
    at Function.Module._resolveFilename (module.js:476:15)
    at Function.Module._load (module.js:424:25)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/user_code/index.js:5:18)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)

"

Any idea how to resolve this?

解决方案

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!

这篇关于如何将MongoDB数据库与dialogfow集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆