Hi there!!
I have a DB where I store locations using GeoJson. Besides that I’m using node-geocoder and mongoose Schemas.
Everything works fine when I save data into the db, but I don’t know how to update the location.
Also I’m using a google api feature that automatically converts the address to lat and lng coords.
My schema looks like this:
const { Schema, model } = require('mongoose');
const geocoder = require('../helpers/geoCoder');
const cocheraSchema = Schema({
nombre: {
type: String,
required: true,
unique: true,
uppercase: true,
trim: true
},
direccion:{
type: String,
required: true,
trim: true
},
location:{
type: {
type: String,
enum: ['Point'],
},
coordinates: {
type: [Number],
required: true
}
}, { timestamps: true })
cocheraSchema.pre('save', async function(next){
const loc = await geocoder.geocode( this.direccion )
this.location = {
type: 'Point',
coordinates: [ loc[0].longitude , loc[0].latitude ]
}
next()
})
cocheraSchema.methods.toJSON = function(){
const { __v, password, _id, ...cochera } = this.toObject();
cochera.id = _id
return cochera;
}
module.exports = model( 'Cochera', cocheraSchema )
So, as you might have seen, before saving the document I’m calling the .pre(‘save’) function to convert the address to the corresponding coords.
How can I do , to update the locations coords when passing the new address ??
I’ cant find anything related to this issue, however I suspect that I got to use some kind of middleware similar to .pre… anyway I’m kinda lost here… need some help pls!