title: How to access mongoose virtuals in express
body: <p>I am trying to build a many to many relationship schema and trying to build a virtual to access the same. Finally trying to get the embedded objects when queried. My schema looks something like below</p>
  
  <pre><code>//Mongoose Schema
  var item1 = new Schema ({
    _id: Number,
    Item2Id: [{type: Number, ref: item2}],
    Detail1: String,
    Detail2: String
    ...
  },{toObject:{virtuals:true},toJSON:{virtuals:true}});
  
  var item2 = new Schema ({
    _id: Number,
    Item1Id: [{type: Number, ref: item1}],
    Detail1: String,
    Detail2: String
    ...
  },{toObject:{virtuals:true},toJSON:{virtuals:true}});
  
  item1.virtual('Item2Details').get(function() {
    var ids = this.Item2Id;
        details = [];
    ids.forEach(function(id, idx, array) {
      item2.findOne({'_id': id}).exec(function (err, doc) {
        details.push(doc);
        if(idx === array.length - 1)
          return details;
      });
    });
  });
  
  //app.js
  app.get('/item1/:id', function(req, res){
    item1.findOne({'_id':req.params.id}).exec(function(err, doc){
      res.send(doc);
    });
  });
  </code></pre>
  
  <p>My expectation was if item1 was</p>
  
  <pre><code>{
    _id:1,
    Item2Id: [2, 3],
    Detail1: 'abc',
    Detail2: 'xyz'
  }
  </code></pre>
  
  <p>and item2 were</p>
  
  <pre><code>{
    _id:2,
    Item2Id: [1],
    Detail1: 'abc',
    Detail2: 'xyz'
  }
  {
    _id:3,
    Item2Id: [1],
    Detail1: 'abc',
    Detail2: 'xyz'
  }
  </code></pre>
  
  <p>resulting response should be</p>
  
  <pre><code>{
    _id:1,
    Item2Id: [2,3],
    Item2Details: [
     {_id:2,
      Item2Id: [1],
      Detail1: 'abc',
      Detail2: 'xyz'},
    {_id:3,
      Item2Id: [1],
      Detail1: 'abc',
      Detail2: 'xyz'}],
    Detail1: 'abc',
    Detail2: 'xyz'
  }
  </code></pre>
  
  <p>However, I am unable to get the same. I tried, using res.send(doc.Item2Details) and no luck. Have also tried using populate in find query, it too fails with some local and foreign error. Assume it is referring to have virtuals defined in different way (<a href="http://mongoosejs.com/docs/populate.html" rel="nofollow noreferrer">http://mongoosejs.com/docs/populate.html</a>), even when I tried it with following link it didn't work.</p>
  
  <pre><code>ref: 'item2',
  localField: '_id',
  foreignField: 'Item2Id'
  </code></pre>
  
  <p>Appreciate any pointer in right direction.</p>