Node.js,Mongo查找并返回数据

时间:2016-02-06 21:31:29

标签: node.js mongodb

在VB6和MySql工作了15年后,我是node和mongo的新手。我确信这不是我的最终程序将使用的,但我需要基本了解如何在另一个模块中调用函数并获得结果。

我希望模块具有打开数据库的功能,在集合中查找并返回结果。我可能想在该模块中为其他集合添加更多功能。现在我需要它尽可能简单,我可以稍后添加错误处理程序等。我花了好几天尝试了不同的方法,module.exports = {...围绕着这个函数而不是它,.send,返回所有方法,没有运气。我知道它是异步的,因此程序可能已经在数据存在之前通过了显示点。

这是我尝试使用Mongo运行db1数据库并使用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);

Console.log(items)在'FindinCol1'调用但不调用console.log(b)(返回'undefined')时工作,所以我没有得到返回,或者我在返回时粘贴它。我已经阅读了数十篇帖子并观看了数十个视频,但我仍然坚持这一点。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:23)

正如另一个答案所提到的,这段代码是异步的,你不能简单地在回调链(嵌套函数)中返回你想要的值。您需要公开一些接口,让您在获得所需值后发出呼叫代码信号(因此,请回调或回调)。

在另一个答案中提供了一个回调示例,但是有一个替代选项绝对值得探索:promises

除了使用所需结果调用的回调函数外,模块还会返回一个可以进入两个状态,即已完成或已拒绝的承诺。调用代码等待承诺进入这两种状态之一,当它执行时调用适当的函数。该模块通过resolvereject触发状态更改。无论如何,这是一个使用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驱动程序对promises有本机支持,你不必做任何工作来包装如上所述的promises中的回调。如果您使用的是最新的驱动程序,这是一个更好的示例:



// 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为异步控制流提供了一种很好的方法,我强烈建议您花一些时间熟悉它们。

答案 1 :(得分:3)

是的,这是一个异步代码,MongoClient根据您放置的位置,您将获得module.exports = { FindinCol1 : function funk1(callback) { 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); return callback(items); }); }); } }; 个对象或什么都没有。

您应该使用回调参数:

FindinCol1

将回调函数传递给a.FindinCol1(function(items) { console.log(items); });

vendor/bin/heroku-php-apache2 web/

我建议你查看这篇文章: https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks