【问题标题】:Using NodeJS promise to query MongoDB使用 NodeJS promise 查询 MongoDB
【发布时间】:2018-09-09 05:32:28
【问题描述】:

我正在使用 WATSON API 构建一个聊天机器人,它发送艺术家数据并提供用户输入。我正在尝试使用 nodejs promise 来查询我的数据库并打印出数据,因为数据库访问是异步的。

所以 artpromise 函数是一个函数,它接受艺术家的名字并查询数据库以将结果保存在 'result' 变量中。然后我尝试打印结果(在聊天机器人中,我实际上将结果打印给用户)。

但是我没有得到我想要的结果并且不断收到语法错误。任何帮助将不胜感激。

let arttistinfo;

function artpromise (artist) {
  return new Promise(function(resolve, reject) {
    const MongoClient = require("mongodb").MongoClient;
    const url = 'mongodb://majac.co.kr:27017/artbot';
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("artbot");
      var query = {name: artist};
      artistinfo = dbo.collection("artistdb").find(query)
        .toArray(function(err, result) {
          if (err) throw reject(err);
          resolve(result);
      });
      db.close();
    }
  });
)};


let artist = "Jan Tarasin";
artpormise.then(function(artist) {
  console.log(result);
});

【问题讨论】:

    标签: node.js mongodb promise chatbot watson


    【解决方案1】:

    MongoDB 节点驱动程序从 v3 开始原生支持 Promise。所以你可以通过使用它们来大大简化你的代码。

    以下是我将如何解决您的问题;

    function artpromise (artist) {
      const MongoClient = require("mongodb").MongoClient;
    
      return MongoClient.connect('mongodb://majac.co.kr:27017')       // connect to mongo server
                        .then(mc => mc.db('artbot')                   // get mongoClient object and connect to artbot db
                                      .collection('artistdb')         // connect to the artistdb collection
                                      .find({name: artist})           // perform your query
                                      .toArray()                      // convert the results into an array
                                      .then(as => (mc.close(), as)))  // close db and return array from query result
                        .catch(e => console.log(e));                  // catch errors
    }
    
    
    let artist = "Jan Tarasin";
    artpromise(artist).then(as => as.forEach(a => console.log(a)));
    
    [nodemon] starting `node maeror.js`
    { _id: 5abdbc18423795deaaff0d8e,
      nationality: 'Polish',
      art_link: 'https://media.mutualart.com/Images/2016_06/29/20/203606422/0532d043-71f6-47bc-945e-aeededd2d483_570.Jpeg',
      years: '1926',
      name: 'Jan Tarasin',
      art_title: ' "Falujące wątki I", 2003 r. ' }
    [nodemon] clean exit - waiting for changes before restart
    

    提醒cursor.toArray() 返回一个promise 可能很有用,因为它必须在构造结果数组之前一次迭代所有查询结果。有时,此操作可能会很耗时,从而导致服务器响应延迟。因此,您可以改为使用cursor.forEach() 方法来像流一样处理从查询返回的文档。这意味着处理第一个文档,然后迭代到下一个文档。这是另一个示例来说明它是如何实现的。

    function artpromise (artist) {
      const MongoClient = require("mongodb").MongoClient;
    
      return MongoClient.connect('mongodb://majac.co.kr:27017')         // connect to mongo server
                        .then(function(mc){
                                var cursor = mc.db('artbot')            // get mongoClient object and connect to artbot db
                                               .collection('artistdb')  // connect to the artistdb collection
                                               .find({name: artist});   // get the cursor
                                return [mc, cursor];                    // return mongoClient and cursor objects
                              });
    }
    
    let artist = "Italian";
    artpromise(artist).then(function([mc,docs]){
                              docs.forEach(doc => console.log(doc),     // process a document and then iterate to the next
                                           ()  => mc.close());          // close db session when all documents are processed
                            })
                      .catch(e => console.log(e));                      // catch errors
    
    [nodemon] starting `node maeror_v2.js`
    { _id: 5abdbc18423795deaafeff13,
      nationality: 'Dutch',
      art_link: 'https://media.mutualart.com/Images/2012_04/15/13/132154856/ddf14e9d-85b1-4b5a-b621-00583e013879_570.Jpeg',
      years: '1839 - 1902',
      name: 'Frederick Hendrik Kaemmerer',
      art_title: ' A Beach Stroll ' }
    [nodemon] clean exit - waiting for changes before restart
    

    【讨论】:

      【解决方案2】:

      我会这样重写,我可以看到您的代码存在少量问题,但现在这对我有用:

      function artpromise (artist) {
        return new Promise(function(resolve, reject) {
          const MongoClient = require("mongodb").MongoClient;
          const url = 'mongodb://majac.co.kr:27017/artbot';
          MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("artbot");
            var query = {name: artist};
            artistinfo = dbo.collection("artistdb").find(query)
              .toArray(function(err, result) {
                if (err) throw reject(err);
                resolve(result);
            });
            db.close();
          });
        });
      };
      
      let artist = "Jan Tarasin";
      artpromise(artist).then(function(result) {
        console.log(result);
      });
      

      我得到以下结果:

      [{
          _id: 5abdbc18423795deaaff0d8e,
          nationality: 'Polish',
          art_link: 'https: //media.mutualart.com/Images/2016_06/29/20/203606422/0532d043-71f6-47bc-945e-aeededd2d483_570.Jpeg',
          years: '1926',
          name: 'JanTarasin',
          art_title: '"Falujace watki I",
          2003r.'
      }]
      

      【讨论】:

      • 我知道艺术家信息没有定义
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      相关资源
      最近更新 更多