remove an embedded document in mongoid

巧了我就是萌 提交于 2019-12-07 06:14:14

问题


I have a projects model with just a name field and in it also the embedded relation to line_items. class Project include mongoid::document field :name embeds_many :line_items end

  class LineItem
   include mongoid::document
   field :title
   embedded_in :project, :inverse_of => :line_items
  end

I suppose this is more of the mongo driver question: if I had such a document

db.project.find()[0]
      {
        _id : 123, 
        name : "housework", 
        line_items:[
         { title : "clean fridge", _id : 601},
         { title : "clean tub",    _id : 602},
         { title : "clean oven",   _id : 603}
        ]
      }
  • 1) How do I update say the line item with id 601 in mongo console?
  • 2) how do I delete it?

Thanks!


回答1:


Current Mongoid (2.0.0) allows:

@category = @list.categories.find(params[:id])
@category.delete

And the resulting database query/update looks like:

MONGODB test['lists'].update({"_id"=>BSON::ObjectId('4d9522315569b11918000019')}, {"$pull"=>{"categories"=>{"_id"=>BSON::ObjectId('4d9523e05569b1191800001f')}}})

Also see the last example on http://mongoid.org/docs/persistence/

Note, I tried variations on this that would have worked with ActiveRecord (@list.categories.delete(xx)) and those do not seem to have any effect.




回答2:


1/ Update :

pro = Project.first
line_item = pro.line_items.find(601)
line_item.title = 'new title'
line_item.save

2/ Delete :

pro = Project.first
line_item = pro.line_items.find(601)
pro.line_item_ids.delete(601)
pro.save



回答3:


Try ...

Update:

db.project.update( { line_items._id : 601 }, { $set : { line_items.title : "new title" } })

Delete:

db.project.update( { $pull : { line_items._id : 601 } })

Sorry about that, try it now?




回答4:


Try:

db.project.update({}, {$set: {line_items: []}});

to remove embedded documents, this will only reset the data inside it to empty but will still retain an empty object in the db which you can repopulate later on.



来源:https://stackoverflow.com/questions/3693842/remove-an-embedded-document-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!