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 :)
As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document.
db.collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method. The following example inserts three new documents into the inventory collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.
Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With