Using async call in mongoose schema pre save function

I installed a pre-save function for my schema, which looks like this:

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 would like to geocode the location address and populate the lat and lng attributes before actually saving the model. The function published above performs geolocation, but this.lat and this.lng are not saved. What am I missing here?

+4
source share
1 answer

You set these fields in the callback geocoder.geocodethere, so it thisno longer refers to your location instance.

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();
  });
});
+5
source

Source: https://habr.com/ru/post/1529293/


All Articles