forest-express-mongoose icon indicating copy to clipboard operation
forest-express-mongoose copied to clipboard

mongoose virtuals are not available to custom fields getter function

Open levynir opened this issue 8 years ago • 4 comments

//models/MyModel.js
const mongoose = require('mongoose');
const MyModelSchema = new mongoose.Schema({
    f1:               { type: String },
},{autoIndex: true, toObject: { virtuals: true }, toJSON: { virtuals: true }});

MyModelSchema.virtual('forest').get( function () {
    return 'found';
});
module.exports = mongoose.model('MyModel',MyModelSchema);

//forest/MyModel.js
const Liana = require('forest-express-mongoose');

Liana.collection('mymodels', {
    fields: [
        {field: 'forest',      type: 'String',  get: o => { return o.forest || 'lost'; }},
    ]
});

//result -> 'lost'

Since the mongoose ResourcesGetter is using lean queries it does not run mongoose virtuals. Please consider adding a flag to allow running mongoose virtuals. This can be done by either removing the lean() from ReasourcesGetter (line 206 on master) or by implementing something similar to mongoose-lean-virtuals npm. Again this should only be done on explicit request from the user (e.g. based on collection settings)

levynir avatar Sep 18 '17 11:09 levynir

Thanks for the feedback @levynir! We'll look into this issue.

arnaudbesnier avatar Sep 20 '17 11:09 arnaudbesnier

Same issue, would be nice to map a GeoJSON location from: {location: {"type":"Point","coordinates":[-11.111111,11.111111]}} to just: {location: {"lat": -11.111111, "lng":11.111111}}

j0nd0n7 avatar Apr 29 '18 03:04 j0nd0n7

As there been a solution or workarounds for this issue?

KudMath avatar Jun 26 '18 15:06 KudMath

@KudMath no fix yet, but feel free to submit a pull request, the liana code is not so complex.

As a workaround, what you can do is re-retrieve the mongoose object with the format you want. You have the id of the document so you can do almost anything the ODM provides:

Liana.collection('mymodels', {
  fields: [{
    field: 'forest',
    type: 'String',
    get: object => { /* Here you can certainly get the id of your document from the "object" argument. */ }
  }],
});

arnaudbesnier avatar Jul 04 '18 05:07 arnaudbesnier