Ruby 如何从Mongoid中删除嵌入的文档?

Ruby 如何从Mongoid中删除嵌入的文档?,ruby,mongodb,mongoid,Ruby,Mongodb,Mongoid,我在使用Mongoid删除文档时遇到一些问题。。。 该代码实际上删除了库,但我收到一个浏览器错误,如下所示: Mongoid::Errors::DocumentNotFound位于/admin/galleries/delete/4e897ce07df6d15a5e000001 可疑代码如下: def self.removeGalleryFor(user_session_id, gallery_id) person = Person.any_in(session_ids: [user_sess

我在使用Mongoid删除文档时遇到一些问题。。。 该代码实际上删除了库,但我收到一个浏览器错误,如下所示:

Mongoid::Errors::DocumentNotFound位于/admin/galleries/delete/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,其中嵌入了许多库

奇怪的是,我已经做了一些测试,效果很好

我真的不知道发生了什么-我的图库看起来很好,甚至从Mongo中删除了

有什么想法吗

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
附言:


在Ruby中,如果找不到具有给定id的文档,则通常在\u score下使用
命名,而不是使用
CamelCase
find
会抛出一个错误。与其检查给定库是否存在,如果不存在则返回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
通过这种方式,您不需要加载Person,甚至不需要将数据从monogdb获取到应用服务器。如果存在库,请将其删除


但是如果你需要调用@fl00r并切换到
destroy
,而不是
delete

的话,你应该更喜欢@fl00r的答案,因为它为我指出了一个至少通过我测试的解决方案——出于某种原因fl00r的代码不起作用——它看起来应该,但出于某种原因不起作用

Person.collection.update(
    {"session_ids" => user_session_id},
    {"$pull" => {'userContent.galleries' => {:_id => gallery_id}}},
    :safe => true
)
=>此代码将通过我的测试,但一旦在sinatra中运行,它就不起作用了。。。。太令人沮丧了


我已经在github上发布了带有测试的代码

谢谢你简洁的回答-是的,我需要控制我的驼峰!您的答案消除了错误,但不幸的是没有删除图库:(谢谢,我试图让您的更新样本继续运行,但没有成功:(-我做了一个示例(包括您的输入)并将其放在github上-谢谢rubish:)我会在有时间时尝试您的建议并发布结果