I am trying to have a function in Node.js with Mongoose that is a .save function for an HTTP request and I am trying to extract the geocoordinates and save them as an array in the Mongoose Schema in MongoDB. However, it seems that I am having a syncing issue because the coordinates are printed as undefined at first and I have to refresh the page to have them displayed. I thought callbacks would solve this, but they do not. (I've added the related code snippets below.) Am I doing something wrong with the callbacks or should I do something else? Thanks in advance!
ArticleProvider.prototype.save = function(articles, callback) {
for( var i =0;i< parties.length;i++ ) {
article = articles[i];
article._id = articleCounter++;
article.created_at = new Date();
if (article.coords === undefined){
geocode(article.address, function(results){
article.coords = results;
});
}
callback(null, articles);
};
var geocoder = require('Geocoder');
function geocode(address, callback) {
geocoder.geocode( address, function( err , data) {
// console.log(data.results[0].geometry.location);
//console.log( [data.results[0].geometry.location.lng, data.results[0].geometry.location.lat]);
var coords = [data.results[0].geometry.location.lng, data.results[0].geometry.location.lat];
console.log(coords);
callback(coords);
});
}