views:

30

answers:

1

When I'm adding a record in mongodb I can specify whatever keys I want and it will store it in the db. The problem is that it will remember those keys for the next time I insert another record. so for example if I do the following:

Product.create :foo => 123

and then

Product.create :bar => 456

I get :foo => nil field in the 2nd record.

This is definitely not a limitation of mongodb itself, since if I restart the rails console and create yet another record with different set of columns, it will not add the columns from the 1st 2 records.

So it seems like mongomapper remembers all the keys used and inserts them all into all records, even if values are not provided.

The question is obviously: how do I disable this crazy attributes explosion?

Basically I want only the 'permanent' keys that I specify in the model to be in every record, but all the 'extra' attributes to be specified per record and not to mess the consequent records.

A: 

When you write to a key, MongoMapper will ensure that they key is defined on the document (as if you had declared it yourself with the key class method). See that code here:

http://github.com/jnunemaker/mongomapper/blob/master/lib/mongo_mapper/plugins/keys.rb#L237

I don't think MongoMapper has any way to distinguish between keys you declared in the class yourself and keys it creates dynamically.

That said, you could always make your own "reset_keys!" method that would destroy the @keys variable in your class and rebuild it again. This is kind of gross, and fragile since we're breaking encapsulation. Here's what it might look like!

class Product
  include MongoMapper::Document

  def self.reset_keys!
    @keys = nil
    key :_id, ObjectId
    key :permanent_biz
    key :permanent_buz
  end

  reset_keys!
end

Product.create :foo => 123
Product.reset_keys!
Product.create :bar => 456

I didn't test this, but what could possibly go wrong?

Jim Garvin