2017-04-14 50 views
2

我尝试从节点JS文件中的mongo DB数据库中恢复对象,但它不起作用。在节点JS上恢复使用MongoDB驱动程序请求的对象

在一个名为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文件中的其他函数中对其进行操作。

回答

0

Then then函数promise返回一个promise。如果在promise内返回一个值,则promise评估的对象是另一个promise,它将解析为返回的值。请参阅this question了解其工作原理的完整说明。

如果您想验证您的代码是否成功获取项目,您将不得不重新组织您的代码以计入的promise s。

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

这应该记录您的项目后,他们从数据库中检索。

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

通常,请记住promise将始终返回promise

0

then()中创建的回调函数是异步的,因此console.log命令执行之前该承诺甚至解决。尝试将其置于回调函数内象下面这样:

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')