Simon Ravelingien
Simon Ravelingien

Reputation: 121

How to use Promise in node js for mongodb query in dialogflow fulfillment with actions-on-google library?

In my dialogflow fulfillment, I want to query a mongodb database and based on the result return an answer. Since I use the actions-on-google database, I must use promises for async calls. How can I do that for a mongodb query?

const express = require("express");
const bodyParser = require("body-parser");
const {dialogflow} = require('actions-on-google');
const app = dialogflow()
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/"

app.intent('Mongodb', (conv) =>{
  MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var query = { address: /^S/ };
  var path;

  db.collection('paths', function(err, collection) {
      collection.find({}).toArray(function(err, results) {
          path = results;
          console.log(results);
      });
  });
  });
  conv.ask(path)
});

Upvotes: 0

Views: 492

Answers (1)

Tyler
Tyler

Reputation: 2390

The Node mongodb package will return a Promise from most (maybe all?) of its callback-based APIs if you don't pass a callback function. For example, you can call db.collection('paths').then(function (collection) { … }). You can then chain the promises like the following:

return MongoClient.connect(url)
  .then(function (client) {
    return client.db('mydb');
  }).then(function (db) {
    return db.collection('paths');
  }).then(function (collection) {
    return collection.find({}).toArray();
  }).then(function (path) {
    conv.ask(path);
  });

You can also use the new Promise((resolve, reject) => …) constructor to wrap anything that is callback based in a Promise API. The Promise documentation on MDN has a good example here.

Upvotes: 2

Related Questions