Anna K
Anna K

Reputation: 1774

Node.js mongodb and promises

I asked my question and I got reffered to another answer but I can not manage it ;( Could someone please help me`?

My orginal question:How to access data from function (node.js)

I tried to do what was suggested. It works untill there is a collection in the mongodb. What would happen if there is no collection? Im getting an error

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

Is there any nice and simple way to ensure that my function will work even there is no collection?

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

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

Upvotes: 1

Views: 40

Answers (1)

Mark
Mark

Reputation: 92440

Yes, there are a couple things you should be doing. First add a catch handler instead of the passing a second function to then for errors on your returned 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')));
});

It's easier to read, but, more importantly, catch() will receive errors that happen in the above then() while the other pattern won't.

Also, I would test for item directly in then() rather than catching the error and acting on it. Using catch this way makes it hard to isolate real errors like a bad DB connection.

Upvotes: 1

Related Questions