2017-04-14 48 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')