简体   繁体   English

使用NodeJS许诺查询MongoDB

[英]Using NodeJS promise to query MongoDB

I am building a chatbot using WATSON API which sends artist data give users' input. 我正在使用WATSON API构建聊天机器人,该机器人发送艺术家数据以提供用户输入。 I am trying to use nodejs promise in order to query my DB and print out the data, since DB accessing is asynchronous. 由于数据库访问是异步的,因此我尝试使用nodejs promise来查询数据库并打印出数据。

So the artpromise function is a function which takes in the artist's name and query the db to save the result in the 'result' variable. 因此artpromise函数是一个函数,它接受艺术家的姓名并查询数据库,以将结果保存在'result'变量中。 Then I am trying to print out the result (in chatbot i actually print out the result to the user). 然后,我尝试打印出结果(在chatbot中,我实际上将结果打印出给用户)。

However I am not getting the result I want and keep getting a syntax error. 但是我没有得到想要的结果,并不断收到语法错误。 Any help would be appreciated. 任何帮助,将不胜感激。

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

I'd rewrite like so, I can see there were a small number of issues with your code, but this works for me now: 我将这样重写,可以看到您的代码存在少量问题,但是现在对我有用:

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

I get the result below: 我得到以下结果:

[{
    _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.'
}]

MongoDB Node driver is natively supporting promises from v3 on. MongoDB节点驱动程序本身就支持从v3开始的承诺。 So you may greatly simplify your code by using them. 因此,通过使用它们,可以大大简化代码。

Here is how i would approach to your problem; 这是我将如何处理您的问题;

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

It might be useful to remind that cursor.toArray() returns a promise as it has to iterate all the query results at once before consturcting the results array. 提醒您cursor.toArray()返回一个promise可能很有用,因为它必须在构造结果数组之前立即迭代所有查询结果。 Sometimes this operation might be time consuming yielding delayed server response. 有时,此操作可能很耗时,导致服务器响应延迟。 So you may instead use the cursor.forEach() method to process the documents returned from the query one by one like a stream. 因此,您可以改为使用cursor.forEach()方法像流一样逐一处理从查询返回的文档。 Which means processing the first document and then iterating to the next one. 这意味着处理第一个文档,然后迭代到下一个文档。 Here is another example to show how it might be implemented. 这是另一个示例,说明如何实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM