在节点JS上恢复使用MongoDB Driver请求的对象

我尝试从一个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); 

结果我有“Promise {}”。 为什么?

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

然后函数调用promise返回一个promise 。 如果一个值在一个promise被返回,那么这个promise的对象是另一个可以parsing返回值的promise 。 看看这个问题的完整解释如何工作。

如果你想validation你的代码是否成功地获取了这些项目,你将不得不重构你的代码来说明promise的结构 。

 var db = require(__dirname+'/model/db.js'); var collection = db.FindinColADSL().then(function(items) { console.log(items); return items; }, function(err) { console.error('The promise was rejected', err, err.stack); }); 

这应该logging您的项目后,从数据库中检索。

承诺以这种方式工作,使asynchronous工作更简单。 如果你把更多的代码放在你的集合代码的下面,它会和你的数据库代码同时运行。 如果你的server.js文件中有其他的函数,你应该可以从你的promise的主体中调用它们。

一般来说,记住一个promise总会回报一个promise

then()中创build的callback函数是asynchronous的,因此在承诺解决之前执行console.log命令。 尝试把它放在callback函数里面,像下面这样:

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

或者,为了另一个例子,使用logging器本身作为callback函数,并显示最后一个console.log调用实际上将在其他调用之前被调用。

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