Node.js mongodb和promise

我问我的问题,我得到了另一个答案,但我不能pipe理它(可有人请帮助我吗?

我的原始问题: 如何从函数(node.js)访问数据

我试图做的build议。 它的工作,直到在MongoDB中有一个集合。 如果没有收集会发生什么? 我得到一个错误

(node:18) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'userName' of undefined 

有什么好的和简单的方法来确保我的function将工作,即使没有收集?

我的indeks.js

 var userID = this.event.session.user.userId; console.log(userID); var self = this; DbConn.dbFind("myUsers", userID).then(function(item) { self.emit(':ask', SpeechOutputUtils.pickRandom(self.t('WELCOME_OK', item.userName)) ); }, function(err) { self.emit(':ask', SpeechOutputUtils.pickRandom(self.t('WELCOME')) ); }); 

我的db.utilis

module.exports = {

  dbFind: function(collectionName, userID) { return MongoClient.connect(url).then(function(db) { var collection = db.collection(collectionName); return collection.findOne({alexaUserID:userID}); }).then(function(item) { return item; }); } }; 

是的,有一些事情你应该做的。 首先添加一个catch处理程序,而不是传递第二个函数, then返回返回的promise中的错误:

 DbConn.dbFind("myUsers", userID) .then(function(item) { if (!item) { // handle emtpy item her instead // of using catch for program flow return } self.emit(':ask', SpeechOutputUtils.pickRandom(self.t('WELCOME_OK', item.userName)) ); }) .catch( function(err) { // this will be an error that happens in the promise or the above then() self.emit(':ask',SpeechOutputUtils.pickRandom(self.t('WELCOME'))); }); 

它更容易阅读,但更重要的是, catch()会接收上面发生的错误then()而另一个模式则不会。

此外,我会直接在then()testingitem ,而不是捕获错误并对其执行操作。 通过这种方式捕获,很难分离真正的错误,如错误的数据库连接。