在猫鼬上填充模型的模型

时间:2013-12-22 21:30:49

标签: node.js mongodb mongoose

我现在已经深入研究了一段时间,发现没有答案有效且没有我想在Google上做的事情所以我来这里问这个问题。

如何填充这样的Schema?

var category_schema = new mongoose.Schema({
  name: {required: true, type: String},
  parent: {type: Number, ref: 'Category' },
  categories: [ {type: Number, ref: 'Category'} ]
});

我现在正在做的是:

Category.find({parent: null}).populate({path: 'categories', model: 'Category'}).exec(function(err, categories) {

但是在控制台上显示类别的console.log:

[ { __v: 2,
    _id: 18,
    name: 'Categoria',
    parent: null,
    categories:
     [ { __v: 1,
         _id: 19,
         name: 'Children',
         parent: 18,
         categories: [Object] }, // <= THIS SHOULD HAVE ACTUAL CATEGORIES
       { _id: 20, name: 'Children 2', parent: 18, __v: 0, categories: [] } ] } ]

非常感谢任何形式的帮助。

感谢。

编辑:

这就是我用来展示的内容

ul.list-group
  if inputs == true
    li.list-group-item
      .radio
        label
          input(type='radio', class='radio', name='parent_id' value='0')
          = 'No category'
  mixin make_list(categories, edit)
    each category in categories
      li.list-group-item
        .radio
          if inputs == true
            input(type='radio', name='parent_id', value='#{category._id}')
          = category.name
  if categories.length
    each category in categories
      li.list-group-item
        .radio
          label
            if inputs == true
              input(type='radio', name='parent_id', value='#{category._id}')
            = category.name
      if category.categories.length
        ul
          +make_list(category.categories, edit)

由于我没有答案,我开始自己挖掘如何做到这一点......

现在,这可能不是最好的方法,但是哦,好吧;

category_schema.static('make_tree', function(callback) {
  Category.find(function(err, categories) {
    var parents_array = [];
    for(var i = 0; i < categories.length; i++) {
      var category = categories[i];
      if (category.parent == null || category.categories.length) {
        categories[i].categories = [];
        parents_array.push(categories[i]);
      }
    }

    for(var x = parents_array.length -1; x >= 0; x--) {
      for(var y = 0; y < categories.length; y++) {
        if (categories[y].parent === parents_array[x]._id) {
          console.log('adding ' + categories[y].name + ' to ' + parents_array[x].name);
          parents_array[x].categories.push(categories[y]);
        }
      }
    }

    console.log(parents_array);
    // Remove parents which have parents. 
    for(var i = parents_array.length - 1; i >= 0; i--) {
      if (parents_array[i].parent) {
        parents_array.splice(i, 1);
      }
    }

    callback(parents_array);
  });
});

事情是......,当我做控制台日志时,我仍然得到这个:

PARENTS ARRAY NOW
[ { __v: 1,
    _id: 23,
    name: 'Categoria',
    parent: null,
    categories: [ { parent: 23, name: 'Hijo', _id: 24, __v: 2, categories: [Object] } ] } ]

1 个答案:

答案 0 :(得分:1)

我认为您可能正在经历节点控制台的变幻莫测。如果你console.log(categories[0].categories)会怎么样? (假设categories是该fisrt对象的名称。