我在更新mongodb中的嵌入式文档时遇到了问题。
我有一个下面的场景。用户模型将地址作为嵌入的文档。
我可以将地址嵌入到父模型即用户模型中,但是即使我嵌入了地址的_id,我仍然不知道如何更新嵌入的地址。
请帮帮忙
谢谢
发布于 2010-07-28 01:11:19
您必须从父级检索嵌入的文档,然后执行更新操作,例如:
address = user.address
address.update_attributes(:street => "foo")发布于 2010-11-05 08:51:34
还有另一种解决方案。如果Person和Preference类之间存在多对多关系,那么:
ruby-1.9.2-p0 > Person.count
=> 0
ruby-1.9.2-p0 > Preference.count
=> 0
ruby-1.9.2-p0 > person = Person.create
=> #< Person _id: 4cd353e92b58af214b000006, preference_ids: []>
ruby-1.9.2-p0 > pref = Preference.create
=> #< Preference _id: 4cd353ee2b58af214b000007, person_ids: [], name: nil>
ruby-1.9.2-p0 >
ruby-1.9.2-p0 > person.preferences << pref
=> true
ruby-1.9.2-p0 > Preference.first.people.count
=> 1
ruby-1.9.2-p0 > Person.first.preferences.count
=> 1
ruby-1.9.2-p0 >
ruby-1.9.2-p0 > person.preferences.first.name = 'foobar'
=> "foobar"
ruby-1.9.2-p0 > person.preferences.first.save
=> true
ruby-1.9.2-p0 > pref.reload
=> #< Preference _id: 4cd353ee2b58af214b000007, person_ids: [BSON::ObjectId('4cd353e92b58af214b000006')], name: "foobar">
ruby-1.9.2-p0 > pref.name
=> "foobar"
https://stackoverflow.com/questions/3345474
复制相似问题