1

This is my MongoDB schema:

var partnerSchema = new mongoose.Schema({
    name: String,
    products: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        }]
});

var productSchema = new mongoose.Schema({
    name: String,
    campaign: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Campaign'
        }
    ]
});

var campaignSchema = new mongoose.Schema({
    name: String,
});


module.exports = {
    Partner: mongoose.model('Partner', partnerSchema),
    Product: mongoose.model('Product', productSchema),
    Campaign: mongoose.model('Campaign', campaignSchema)
}

And I'd like to send all documents (partner>product>campaign) to my View as a one object.

I know how to send partner with product ref. For example:

var campSchema = require('../model/camp-schema');
router.get('/partner-list', function (req, res) {
    campSchema.Partner.find({}, function (err, partnerList) {
        if (err) throw err;
        res.json({ partnerList: partnerList });
    }).populate('products');
});

And I can easily iterate at view in this way:

   li(ng-repeat="product in partner.products")
       a(href="#") {{ product.name }}

And here is the question. How can I pass ONE object as a document with partner, product and campaign. Because at the moment I have only partner and product in that object.

DiPix
  • 5,755
  • 15
  • 61
  • 108
  • Try this one : `.populate('products','products.campaign')` (probably would not work, but worth trying I think. – libik Jun 23 '16 at 14:03

1 Answers1

0

You can use this pattern to populate the nested campaign model:

var campSchema = require('../model/camp-schema');
router.get('/partner-list', function (req, res) {
    campSchema.Partner
        .find({})
        .populate({
            path: 'products',
            model: 'Product',
            populate: {
                path: 'campaign',
                model: 'Campaign'
            }
    }).exec(function(err, partnerList) {
        if (err) throw err;
        res.json({ partnerList: partnerList });
    });
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • I don't why but `.exec` doesn't work correctly. Error: `Expected ';'` http://prntscr.com/bk2aun Did I miss something? – DiPix Jun 23 '16 at 15:34
  • @DiPix Apologies, I had left out the callback function. It should work now. – chridam Jun 23 '16 at 16:02
  • Thank you. Now I wondering how to remove object. If you can, then check this post: http://stackoverflow.com/questions/38011068/how-to-remove-object-taking-into-account-references-in-mongoose-node-js – DiPix Jun 24 '16 at 10:22