Node.js,Mongo查找并返回数据 [英] Node.js, Mongo find and return data

查看:77
本文介绍了Node.js,Mongo查找并返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用VB6和MySql 15年之后,我对Node和mongo还是陌生的.我确定这不是我的最终程序将要使用的,但是我需要对如何在另一个模块中调用函数并返回结果有一个基本的了解.

I’m new to node and mongo after 15 years of VB6 and MySql. I’m sure this is not what my final program will use but I need to get a basic understanding of how to call a function in another module and get results back.

我希望模块具有打开数据库,在集合中查找并返回结果的功能.我可能还想在该模块中为其他集合添加更多功能.现在,我需要尽可能简单,以后可以添加错误处理程序等.我花了几天的时间在函数周围尝试不同的方法,module.exports = {…,如果没有,.send,万事大吉.我了解它是异步的,因此程序可能在数据到达之前就已经通过了显示点.

I want a module to have a function to open a DB, find in a collection and return the results. I may want to add a couple more functions in that module for other collections too. For now I need it as simple as possible, I can add error handlers, etc later. I been on this for days trying different methods, module.exports={… around the function and with out it, .send, return all with no luck. I understand it’s async so the program may have passed the display point before the data is there.

这是我在Mongo上尝试运行的数据库,其中db1数据库具有col1集合.

Here’s what I’ve tried with Mongo running a database of db1 with a collection of col1.

Db1.js
var MongoClient = require('mongodb').MongoClient;
module.exports = {
    FindinCol1 : function funk1(req, res) {
    MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) {
            if (err) {
                return console.dir(err);
            }
            var collection = db.collection('col1');
            collection.find().toArray(function (err, items) {
                    console.log(items);
                   // res.send(items);
                }
            );
        });
    }
};


app.js
a=require('./db1');
b=a.FindinCol1();
console.log(b);

当'FindinCol1'调用而不是console.log(b)(返回'undefined')时,Console.log(items)起作用,因此我没有得到返回或在返回时将其粘贴.我已经阅读了数十篇文章,并观看了数十部视频,但是我仍然停留在这一点上.任何帮助将不胜感激.

Console.log(items) works when the 'FindinCol1' calls but not console.log(b)(returns 'undefined') so I'm not getting the return or I'm pasted it by the time is returns. I’ve read dozens of post and watched dozens of videos but I'm still stuck at this point. Any help would be greatly appreciated.

推荐答案

如另一个答案所述,此代码是异步的,您不能简单地在回调链(嵌套函数)中返回想要的值.您需要公开一些接口,以便在您拥有所需的值(因此,将其回调或回调)后,用信号通知调用代码.

As mentioned in another answer, this code is asynchronous, you can't simply return the value you want down the chain of callbacks (nested functions). You need to expose some interface that lets you signal the calling code once you have the value desired (hence, calling them back, or callback).

另一个答案中提供了一个回调示例,但是绝对值得探索另外一个选择:

There is a callback example provided in another answer, but there is an alternative option definitely worth exploring: promises.

该模块将返回一个可以输入两种状态(已实现或已拒绝)的promise,而不是您使用所需结果调用的回调函数.调用代码等待承诺进入这两种状态之一,当它执行时将调用适当的函数.模块通过resolve ing或reject ing触发状态更改.无论如何,这是一个使用promises的示例:

Instead of a callback function you call with the desired results, the module returns a promise that can enter two states, fulfilled or rejected. The calling code waits for the promise to enter one of these two states, the appropriate function being called when it does. The module triggers the state change by resolveing or rejecting. Anyways, here is an example using promises:

Db1.js:

// db1.js
var MongoClient = require('mongodb').MongoClient;
/*
node.js has native support for promises in recent versions. 
If you are using an older version there are several libraries available: 
bluebird, rsvp, Q. I'll use rsvp here as I'm familiar with it.
*/
var Promise = require('rsvp').Promise;

module.exports = {
  FindinCol1: function() {
    return new Promise(function(resolve, reject) {
      MongoClient.connect('mongodb://localhost:27017/db1', function(err, db) {
        if (err) {
          reject(err);  
        } else {
          resolve(db);
        }        
      }
    }).then(function(db) {
      return new Promise(function(resolve, reject) {
        var collection = db.collection('col1');
        
        collection.find().toArray(function(err, items) {
          if (err) {
            reject(err);
          } else {
            console.log(items);
            resolve(items);
          }          
        });
      });
    });
  }
};


// app.js
var db = require('./db1');
    
db.FindinCol1().then(function(items) {
  console.info('The promise was fulfilled with items!', items);
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

现在,更多最新版本的node.js mongodb驱动程序已对Promise提供本机支持,您无需做任何工作即可将回调包装在上述Promise中.如果您正在使用最新的驱动程序,那么这是一个更好的示例:

Now, more up to date versions of the node.js mongodb driver have native support for promises, you don't have to do any work to wrap callbacks in promises like above. This is a much better example if you are using an up to date driver:

// db1.js
var MongoClient = require('mongodb').MongoClient;
                       
module.exports = {
  FindinCol1: function() {
    return MongoClient.connect('mongodb://localhost:27017/db1').then(function(db) {
      var collection = db.collection('col1');
      
      return collection.find().toArray();
    }).then(function(items) {
      console.log(items);
      return items;
    });
  }
};


// app.js
var db = require('./db1');
    
db.FindinCol1().then(function(items) {
  console.info('The promise was fulfilled with items!', items);
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

Promise为异步控制流提供了一种极好的方法,我强烈建议您花一些时间来熟悉它们.

Promises provide an excellent method for asynchronous control flow, I highly recommend spending some time familiarizing yourself with them.

这篇关于Node.js,Mongo查找并返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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