如何从Mongoid中删除嵌入式文档?
我在使用Mongoid ... 的代码实际上并删除图库一些问题删除我的文档,但我得到一个浏览器错误,它看起来像:如何从Mongoid中删除嵌入式文档?
Mongoid ::错误:: DocumentNotFound在/管理员/画廊/删除/ 4e897ce07df6d15a5e000001
嫌疑代码如下:
def self.removeGalleryFor(user_session_id, gallery_id)
person = Person.any_in(session_ids: [user_session_id])
return false if person.count != 1
return false if person[0].userContent.nil?
return false if person[0].userContent.galleries.empty?
gallery = person[0].userContent.galleries.find(gallery_id) #ERROR is on this line
gallery.delete if !gallery.nil?
end
我Person类嵌入一个userContent其中嵌入了许多画廊。
奇怪的是我有一对夫妇的解决此其做工精细的测试...
我真的不知道发生了什么 - 我的画廊似乎找到罚款,甚至从蒙戈删除。
任何想法?
def self.removeGalleryFor(user_session_id, gallery_id)
# person = Person.where(session_ids: user_session_id).first
person = Person.any_in(session_ids: [user_session_id])
if person && person.userContent && person.userContent.galleries.any?
gallery = person.userContent.galleries.where(id: gallery_id).first
gallery.delete if gallery
end
end
PS:
在Ruby中通常under_score
命名而不是用于CamelCase
find
抛出一个错误,如果它不能找到给定id的文档。不要检查给定图库的存在,如果不存在则返回nil,而是在询问删除任何此类图库时直接询问mongodb。
def self.remove_gallery_for(user_session_id, gallery_id)
user_session_id = BSON::ObjectId.from_string(user_session_id) if user_session_id.is_a?(String)
gallery_id = BSON::ObjectId.from_string(gallery_id) if gallery_id.is_a?(String)
# dropping to mongo collection object wrapped by mongoid,
# as I don't know how to do it using mongoid's convenience methods
last_error = Person.collection.update(
# only remove gallery for user matching user_session_id
{"session_ids" => user_session_id},
# remove gallery if there exists any
{"$pull" => {:userContent.galleries => {:gallery_id => gallery_id}}},
# [optional] check if successfully removed the gallery
:safe => true
)
return last_error["err"].nil?
end
这样你不加载人,你甚至不会从monogdb到应用程序服务器的数据。只要将画廊删除,如果它存在。
但是,你应该更喜欢@ fl00r的答案,如果你需要火的回调,并切换到destroy
,而不是delete
谢谢rubish :)我会尝试你的建议,当我获得了一些时间并发布结果 –
荣誉给Rubish指着我,至少经过我的测试解决方案 - 由于某种原因fl00r的代码没“T工作 - 它看起来像它应该,但不会出于某种原因...
Person.collection.update(
{"session_ids" => user_session_id},
{"$pull" => {'userContent.galleries' => {:_id => gallery_id}}},
:safe => true
)
=>此代码将通过我的测试,但后来,一旦它在运行西纳特拉它不工作.. ..太令人沮丧了!
已经发布此代码测试在github https://github.com/LouisSayers/bugFixes/tree/master/mongoDelete
感谢您的令人满意的答案 - 是的,我需要控制我的骆驼驼峰! 你的答案摆脱了错误,但不幸的是不删除画廊:( –
什么错误?这是一些misstype这里 – fl00r
谢谢,我试图让你的更新样本去,但它没有工作:( - 我做了一个例子(包括你的输入),并把它放在github上 - https://github.com/LouisSayers/bugFixes/tree/master/mongoDelete –