TypeError: Cannot read property 'dataSources' of undefined

464 views
Skip to first unread message

Sandeep Manne

unread,
Mar 31, 2015, 5:12:21 AM3/31/15
to loopb...@googlegroups.com
I am getting 

TypeError: Cannot read property 'dataSources' of undefined error when I am trying to run rest datasource

Here is my code

module.exports = function(Account) {
var cloudantService;

Account.login = function(next, mode) {
console.log("> Account before create called");
var cloudantService = Account.app.dataSources.cloudant;
cloudantService.login(function(err, response, context){
if (err) throw err;
if (response.error) {
next('> response error');
}
console.log(response);
console.log("Response fetched");
next();
});
};

Account.login();
};


Here is my datasource.json

{
"db": {
"name": "db",
"connector": "memory"
},
"cloudant": {
"name": "cloudant",
"connector": "rest",
"operations": [
{
"template": {
"method": "POST",
"url": "http://xxx.xxxx.com/xxx",
"json": true,
"body": {
"loginId": "smanne",
"password": "xxxxx"
},
"functions" : {
"restLogin":[]
}
}
}
]
}
}

twilk...@strongloop.com

unread,
Apr 1, 2015, 2:39:13 PM4/1/15
to loopb...@googlegroups.com
Okay, this is a good one!

Account is a model, and the code that he is showing is probably in his Account.js file.  

The reason his code is failing is that it is a timing issue.   When he is executing his call login(), the datasource has not been initialized yet.  So he needs to setup an event listener on the data source.  You do that with code like the following:

Account.datasources.cloudant.once('connected', function () {
Account.login();
});

This says, once the datasource it connected, then execute the login() function.

The key to remember, all for `model.js` files are executed at server start, in "parallel" with everything else.  Thus, you have to wait for some events to happen before you can do other things. ;-)
Reply all
Reply to author
Forward
0 new messages