novon
novon

Reputation: 993

Using async call in mongoose schema pre save function

I've set up a pre save function for my schema which looks like so:

LocationSchema.pre('save', function(next) {
  geocoder.geocode(this.address, function ( err, data ) {
    if(data && data.status == 'OK'){
      //console.log(util.inspect(data.results[0].geometry.location.lng, false, null));

      this.lat = data.results[0].geometry.location.lat;
      this.lng = data.results[0].geometry.location.lng;
    }

    //even if geocoding did not succeed, proceed to saving this record
    next();
  });
});

So I'd like to geocode a location address and populate the lat and lng attributes before actually saving the model. In the function I posted above the geolocation works but this.lat and this.lng don't get saved. What am I missing here?

Upvotes: 4

Views: 1540

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You're setting those fields in the geocoder.geocode callback there so this isn't referencing your location instance anymore.

Instead, do something like:

LocationSchema.pre('save', function(next) {
  var doc = this;
  geocoder.geocode(this.address, function ( err, data ) {
    if(data && data.status == 'OK'){
      doc.lat = data.results[0].geometry.location.lat;
      doc.lng = data.results[0].geometry.location.lng;
    }
    next();
  });
});

Upvotes: 5

Related Questions