MokoJs / moko

Generator powered models
51 stars 3 forks source link

nested document #8

Open xaevir opened 10 years ago

xaevir commented 10 years ago

Hello. I love the simplicity of moko. I was wondering if it supports nested documents?

rschmukler commented 10 years ago

Hey! It currently does not, but I'd definitely love to see a plugin that adds support. I think it'd be pretty easy with the events... Basically:

User.use(embeds())

var Food = moko('Food'),
      Account = moko('Account');

User.attr('account', { embeds: Account })
User.attr('favoriteFoods', { embeds: Food })

Embeds plugin would look something like this....


module.exports = function() {
  var attrs = {};
  return function(Model) {
    Model.on('attr', function(attr, opts) {
      if(opts.embeds) { attrs[attr] = opts.embeds; } // listen for new attrs
    }

    for(var attr in Model.attrs) {
      if(opts.embeds) { attrs[attr] = opts.embeds; } // check already existing attrs
    }

    Model.on('initializing', function*(instance) {
      for(var attr in attrs) { 
        if(instance[attr]) instance[attr] = attrs[attr](instance[attr])
      }
    })
  };
};

Then just add a few events for things like saving, etc.

For more details see the plugin creation guide.

Let me know if you have questions!

paglias commented 10 years ago

@rschmukler array of embedded documents would also be very useful