personally this seems very odd to me. I'm currently querying my Elastic search database to get some indexed records, everything works fine and I get my response back filled with hits.
Now I would like to manipulate the response and add a string to the JSON object after I've got the document back from elastic search. Currently this is my code:
var list = response.hits.hits;
for (var i = 0; i < list.length; i++) {
var compSlug = '';
var query = Company.findById(list[i]._id);
var promise = query.exec();
promise.then(function(comp) {
list[i]._source.slug = comp.slug;
});
console.log(list[i]._source); // this is line 142
console.log(list[i]._source.title); // this is line 143
}
This code, the console.log(list[i]._source);
displays what I'm expecting to see, the entire indexed document. But the other console.log with list[i]._source.title
returns undefined.
Also I get the following error: Unhandled rejection TypeError: Cannot read property '_source' of undefined
on the last console.log
line.
Below is the full stack trace of the error:
Unhandled rejection TypeError: Cannot read property '_source' of undefined
at search.controller.js:143:11
at tryCatcher (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/promise.js:504:31)
at Promise._settlePromise (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/promise.js:561:18)
at Promise._settlePromise0 (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/promise.js:606:10)
at Promise._settlePromises (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/promise.js:685:18)
at Async._drainQueue (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues [as _onImmediate] (/Users/lucaswelander/Desktop/tsearch/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate [as _immediateCallback] (timers.js:383:17)
Why do I get the error on line 143 but not on line 142? It must be something with that ._source is undefined obviously, but why do I get this error when I clearly see that _source is not undefined?