mongoosejs / mongoose-lean-virtuals

Attach virtuals to the results of mongoose lean() queries
Apache License 2.0
45 stars 24 forks source link

Subdocument schema virtuals not coming. #20

Closed arpitbhs closed 5 years ago

arpitbhs commented 5 years ago

If I have a child schema nested within the main schema, the virtual defined on the child schema doesnt come.

eg.

const mongoose = require('mongoose');
const leanVirtualPlugin = require('mongoose-lean-virtuals');

const childSchema = new mongoose.Schema({
  name: {
    type: String
  }
}, {
  timestamps: true,

  toObject: {
    virtuals: true
  },
  toJSON: {
    virtuals: true
  }
});

childSchema.virtual('something').get(function() {
  return 'something';
});

const mainSchema = new mongoose.Schema({
  name: {
    type: String
  },
  children: [childSchema]
}, {
toObject: {
    virtuals: true
  },
  toJSON: {
    virtuals: true
  }
});

mainSchema.virtual('main').get(function() {
  return 'main';
});

mainSchema.virtual('children.someOtherThing').get(function() {
  return 'someOtherThing';
});

mainSchema.set('collection', 'test');
mainSchema.plugin(leanVirtualPlugin);
const TestModel =  mongoose.model('test', mainSchema);

Now TestModel.find().lean({virtuals:true}).exec() , gives me the 'main' virtual, also 'someOtherThing' virtual as a key of children (not for each array item). But it doesnt give me the child virtual 'something' on each element of the children array. Like -

_id: 5c8955801b7d3179990b2150, name: 'hello', children: [ { _id: 5c8955801b7d3179990b2152, name: 'child1', }, { _id: 5c8955801b7d3179990b2151, name: 'child2', }, someOtherThing: 'someOtherThing' ], main: 'main',

vkarpov15 commented 5 years ago

Mongoose doesn't support declaring virtuals on child schemas using this syntax, you would need to define the someOtherThing virtual on childSchema:

childSchema.virtual('someOtherThing').get(function() {
  return 'someOtherThing';
});
arpitbhs commented 5 years ago

As mentioned in my inital post, I have declared something on the childSchema itself like childSchema.virtual('something').get(function() { return 'something'; }); It still wont appear

arpitbhs commented 5 years ago

Bump! Any help @vkarpov15 ? I was doing exactly the same thing as you suggested (defining the virtual on the child schema). You didn't read the full post.

vkarpov15 commented 5 years ago

I'll check this out. FYI I view GitHub notifications oldest first, so 'bump' messages bump you to the back of the queue, not the front.

arpitbhs commented 5 years ago

Got it, thanks!