mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Unable to refer virtual field on hydrate.toObject

Open einsub opened this issue 7 years ago • 1 comments

I performed an aggregation query to get the store's distance. Then I tried to use the distance by defining a virtual field in the store. But the distance is undefined. I wonder if there is a mistake in the code or if there is no choice.

mongoose 5.4.21 MongoDB 4.0.3

const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true)

const storeSchema = new mongoose.Schema({
  name: String,
  location: {
    type: {
	  type: String
	},
    coordinates: [Number]
  }
}, {
  toObject: {
	virtuals: true
  },
  toJSON: {
	virtuals: true
  }
})
storeSchema.index({ location: '2dsphere' })
storeSchema.virtual('isAvailable').get(function () {
  console.log('----------------------------------------------')
  console.log(`distance is ${this['distance']} in virtual method`)
  console.log(`distance is ${this.distance} in virtual method`)
  console.log('----------------------------------------------')
  return (this.distance < 100)
})
const Store = mongoose.model('Store', storeSchema);

(async () => {
  const conn = await mongoose.connect('mongodb://localhost/dev', { useNewUrlParser: true });
  await new Store({
    name: 'Cafe',
    location: {
      type: 'Point',
      coordinates: [126.8990639, 33.4397954]
    }
  }).save();
  const stores = await Store.aggregate([{
    $geoNear: {
      spherical: true,
      limit: 1,
      maxDistance: 10000,
      near: {
        type: 'Point',
        coordinates: [126.876933, 33.381018]
      },
      distanceField: 'distance',
      key: 'location'
    }
  }]) 
  
  const store = Store.hydrate(stores[0]).toObject({ virtuals: true, getters: true })
  console.log('----------------------------------------------')
  console.log(`distance is ${store.distance} after hydrated`)
  console.log('----------------------------------------------')
  console.log(`is avaiable: ${store.isAvailable}`)
  await conn.disconnect();
})();
----------------------------------------------
distance is undefined in virtual
distance is undefined in virtual
----------------------------------------------
----------------------------------------------
distance is 6858.597026847846 after hydrated
----------------------------------------------
is avaiable: false

einsub avatar Apr 03 '19 18:04 einsub

I looked more closely and unfortunately this is expected behavior, not a bug in Mongoose. That's because distance is not in your schema. There's 2 ways you can work around this:

  1. Add distance: Number to your schema:
const storeSchema = new mongoose.Schema({
  name: String,
  location: {
    type: {
          type: String
        },
    coordinates: [Number],
  },
  distance: Number
}, {
  toObject: {
        virtuals: true
  },
  toJSON: {
        virtuals: true
  }
})
  1. Use Document#get() to get the value.
storeSchema.virtual('isAvailable').get(function () {
  console.log('----------------------------------------------')
  console.log(`distance is ${this.get('distance')} in virtual method`)
})

Mongoose doesn't create getters for properties that aren't in the schema, so you need to explicitly .get() those properties.

vkarpov15 avatar Apr 10 '19 15:04 vkarpov15