【问题标题】:how to integrate MongoDB database with dialogfow如何将 MongoDB 数据库与对话流集成
【发布时间】:2019-05-07 18:33:25
【问题描述】:

我有一个 webhook 应用程序,我已成功从 Firebase 数据库中检索到数据。但我需要合并 MongoDB。这是目前为止的代码。

  '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);

});

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

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)

"

知道如何解决这个问题吗?

【问题讨论】:

  • 你的mongodb连接代码成功了吗?您是否使用内联编辑器或 webhook 来实现?
  • 我使用的是 webhook,而不是内联编辑器。 mongo db 代码还不完整。我不知道如何使用 mongodb 提取数据。这就是为什么要问我应该如何实现它?

标签: node.js mongodb dialogflow-es


【解决方案1】:

按照步骤将 MongoDB(使用 Mongoose)连接到您的 Dialogflow。我将继续使用您提供的代码。

代码

'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 日志

Google 助理输出

注意事项:

  1. 如果您的 MongoDB 数据库托管在外部网络上,则它是 必须使用Billing Firebase Account (非常重要)
  2. 请参阅Mongoose Docs 了解更新和删除操作等更多功能。
  3. 您不一定需要 MVC 结构来将 MongoDB 连接到 Dialogflow。
  4. 确保通过在函数文件夹中运行 npm install mongoose --save 在 package.json 中添加 mongoose。这将解决诸如Cannot find module mongoose 之类的问题。

希望有帮助!

【讨论】:

  • 如何在 package.json 中添加猫鼬?
  • 如果您使用 webhook fullfilment,请使用 npm install --save mongoose 安装 mongoose
  • 已经完成了。但我收到一个错误。 “!functions[dialogflowFirebaseFulfillment]:部署错误。函数加载错误:文件 index.js 中的代码无法加载。您是否在 package.json 依赖项中列出了所有必需的模块?”
  • 您可以编辑您的问题以提供 package.json 吗?尝试在您的函数文件夹中运行npm install mongoose --save
  • 这行得通。你是如何把它作为帖子的答案的?非常感谢。
猜你喜欢
  • 2019-11-05
  • 1970-01-01
  • 2018-12-09
  • 2017-01-11
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2019-09-05
相关资源
最近更新 更多