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", 开发者_JAVA技巧_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!
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.
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
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?
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.
精彩评论