Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove an embedded document in mongoid

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!

like image 290
Nik So Avatar asked Sep 12 '10 05:09

Nik So


2 Answers

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.

like image 178
Hollownest Avatar answered Sep 27 '22 19:09

Hollownest


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
like image 36
shingara Avatar answered Sep 27 '22 18:09

shingara