Thursday 4 May 2017

Populate a Nested Mongoose Object w/ a Nested Object

Working on my first project and have been stumped on this for a couple days.

I'm trying to populate an object that contains the brewery info and the single corresponding beer from the Beer model.

models.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var beerSchema = Schema({
    breweryName: String,
    beer: [{
        beerName: String
    }]
});

var draftlistSchema = Schema ({
    userName: String,
    tap: [{
        tapNo: Number,
        _tapBeer: { type: Schema.Types.ObjectId, ref: 'Beer' },
        tapStatus: String
    }]
});

var Draftlist = mongoose.model('Draftlist', draftlistSchema);
var Beer = mongoose.model('Beer', beerSchema);

module.exports = {
    Draftlist: Draftlist,
    Beer: Beer
    }

route.js

var getDraftlist = function(user, callback) {
  models.Draftlist.findOne({ 'userName': user }).populate( {
    path: 'tap._tapBeer',
    model: 'Draftlist'
    }).exec(function(err, draftlist) {
    // console.log(draftlist.tap)
    console.log(draftlist);
    callback(draftlist);      
  });
};`

I'm getting a null returned with the current code. Ideally I would like the returned object to look something like--

{
breweryName: Some Brewery,
beer: {// Beer object that was referenced by Id //}
}



via BHalvy82

No comments:

Post a Comment