These are chat archives for Automattic/mongoose

29th
Sep 2015
Eric Martinez
@ericmartinezr
Sep 29 2015 17:51

Hey guys, I have this code

var Category = require(__dirname + '/db/models/category');
var Subforum = require(__dirname + '/db/models/subforum');
//...
var category = new Category({name: 'CATEGORY1'});
category.save();

var subforums = [
    {name: 'SUBFORUM1', category : category._id},
    {name: 'SUBFORUM2', category : category._id}
];
Subforum.collection.insert(subforums);

And I'm trying to retrieve the category and its subforums

    Category.find({}).populate('subforums').exec(function(err, ct) {
        if(err) throw err;
        console.log(ct);
    });
    // prints :
    /*
    { _id: 560acb995384a35c06ac83e0,
      name: 'CATEGORY1',
      __v: 0,
      subforums: [] // This should not be empty AFAIK
     }
    */

These are the schemas

// Category
var CategorySchema = new mongoose.Schema({
    name : String,
    creation_date : Date,
    subforums : [{type:mongoose.Schema.Types.ObjectId, ref: 'Subforum'}]
});
module.exports = mongoose.model('Category', CategorySchema);

// Subforum
var SubforumSchema = new mongoose.Schema({
    name : String,
    creation_date : Date,
    category : {type: mongoose.Schema.Types.ObjectId, ref: 'Category', childPath : 'subforums'},
    topics : [{type: mongoose.Schema.Types.ObjectId, ref : 'Topic'}]
});
module.exports = mongoose.model('Subforum', SubforumSchema);

Why am I getting an empty subforums array? Any idea?

Sorry for the long post, I'll give you a cookie if you help me :(
Eric Martinez
@ericmartinezr
Sep 29 2015 19:13
Nevermind, I got it like this
        var category = new Category({name: 'CATEGORY1'});
        var subforums = [
            {name: 'SUBFORUM1', category : category._id},
            {name: 'SUBFORUM2', category : category._id}
        ];
        Subforum.collection.insert(subforums, function(err, sfs) {
            for(var i = 0; i < sfs.ops.length; i++) {
                category.subforums.push(sfs.ops[i]);
            }
            category.save();
        });