larryzhao
larryzhao

Reputation: 3213

Mongodb - create a new document in an embedded array

I have following User model, embeds the Category model,

class User
  include Mongoid::Document
  include BCrypt

  field :email,           :type => String
  field :password_hash,   :type => String
  field :password_salt,   :type => String

  embeds_many :categories
  embeds_many :transactions
  ....
   end

My question is, I just found that if I use the code:

me = User.where("some conditions")
me.categories << Category.new(:name => "party")

everything works fine, but if I use the .create method:

me = User.where("some conditions")
me.categories << Category.create(:name => "party")

I will get an exception:

undefined method `new?' for nil:NilClass

Anyone knows why is that? And from mongoid.org http://mongoid.org/docs/persistence/standard.html, I could see that .new and .create actually generates the same mongo command.

Needs help, thanks :)

Upvotes: 5

Views: 2608

Answers (1)

RameshVel
RameshVel

Reputation: 65877

Create immediately persist the document into mongo. Since the category document is within another document (as embedded) you cannot save it separately. Thats why you are getting the error.

For more clarity, assume embedded document as a field in the parent document which contains sub fields. Now you can easily understand that you cannot save a field without a document. right?

Other hand new  initialize the document class and will be only inserted into the parent doc when using <<.

Category.create(:name => "party")
>>NoMethodError: undefined method `new?' for nil:NilClass

is equivalent to

 c = Category.new(:name => "party")
 c.save
 >>NoMethodError: undefined method `new?' for nil:NilClass

Hope this helps

Upvotes: 10

Related Questions