Node.js 在节点JS上恢复MongoDB驱动程序请求的对象

Node.js 在节点JS上恢复MongoDB驱动程序请求的对象,node.js,mongodb,Node.js,Mongodb,我尝试从mongo DB数据库中恢复对象,在一个节点JS文件中,但它不起作用 在名为db.js的文件中,我编写了以下代码: var MongoClient = require('mongodb').MongoClient; module.exports = { FindinColADSL: function() { return MongoClient.connect("mongodb://localhost/sdb").then(function(db) { var

我尝试从mongo DB数据库中恢复对象,在一个节点JS文件中,但它不起作用

在名为db.js的文件中,我编写了以下代码:

var MongoClient = require('mongodb').MongoClient;

module.exports = {
  FindinColADSL: function() {
    return MongoClient.connect("mongodb://localhost/sdb").then(function(db) {
      var collection = db.collection('scollection');

      return collection.find({"type" : "ADSL"}).toArray();
    }).then(function(items) {
      return items;
    });
  }
};
我尝试在文件server.js中使用它:

var db = require(__dirname+'/model/db.js');

var collection = db.FindinColADSL().then(function(items) {
 return items;
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

console.log(collection);
结果我得到了“承诺{}”。为什么?


我只想从数据库中获取一个对象,以便在server.js文件中的其他函数中操作它。

然后
然后
调用
promise
s的函数返回一个
promise
。如果在
承诺
中返回值,则
承诺
计算结果的对象是另一个
承诺
,该对象解析为返回的值。请看一看,以获得有关其工作原理的完整解释

如果您想验证您的代码是否成功获取项目,则必须重新构造代码,以考虑
promise
s。

从数据库检索项目后,应记录这些项目

承诺以这种方式工作,使异步工作更加简单。如果在集合代码下面放置更多代码,则它将与数据库代码同时运行。如果server.js文件中有其他函数,则应该能够从
promise
s的主体中调用它们


通常,请记住
promise
将始终返回
promise
then()
中创建的回调函数是异步的,因此使得
控制台.log
命令在promise解析之前执行。请尝试将其放置在回调函数中,如下所示:

var collection = db.FindinColADSL().then(function(items) {
  console.log(items)
  return items;
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});
或者,在另一个示例中,使用记录器函数本身作为回调函数,并显示最后一个
console.log
调用实际上将在其他调用之前被调用

db.findinColADSL()
  .then(console.log)
  .catch(console.error)
console.log('This function is triggered FIRST')
db.findinColADSL()
  .then(console.log)
  .catch(console.error)
console.log('This function is triggered FIRST')