Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoid new versus build

why mongoid dosen't insert id when calling new on an association, but inserts id when calling build on an association?

Is this a bug or this is how it works in mongoid?

like image 612
Gagan Avatar asked Dec 12 '25 00:12

Gagan


1 Answers

this is the same behaviour your get with other ORMs, e.g. SQLite ... #new does not create an ID because the new object hasn't been saved / persisted yet!

Whenever a save happens, the next available ID is used for the newly saved object... that means if you had a couple of new objects, you could not assign them an ID until they are saved, because the ID depends on the order they are saved in..

MongoDB IDs are not incremented as IDs in SQL DBs, but they contain a time stamp as part of the key.. hence again the dependency on the order of saving / persisting the objects

Also: the IDs only make sense as a reference to saved objects -- you could create objects with #new and end up not saving them -- it would not make sense to assign an ID to an un-saved object.

like image 133
Tilo Avatar answered Dec 14 '25 10:12

Tilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!