Question

I have a collection of records which have certain specific properties that I need for internal use, however when I send the results back to the user I would like these properties to be re-arranged.

Specifically I have a geo array that I would like to break up into lat and lng properties.

I am using Mongoose, and was wondering if there was a way to use a pre/post hook (I've used it for 'save') on record results during searches, to modify the records before the results are returned.

So, in the DB if we had:

{
  name: 'Foo Bar',
  geo: [-0.12, 32.17]
},
{
  name: 'Pizza',
  geo: [-0.09, 34.51]
}

The results from the query would be:

{
  name: 'Foo Bar',
  lat: 32.17,
  lng: -0.12
},
{
  name: 'Pizza',
  lat: 34.51,
  lng: -0.09
}

Any ideas how to do this?

Was it helpful?

Solution

Yeah on your model definition use the post-init event to do that transformation. More info here: http://mongoosejs.com/docs/middleware.html#post

Schema
    .post('init', function (doc) {
        //do your stuff

    })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top