我无法解决删除嵌入式文档的问题 - 即使发现父级和嵌入式文档很难发生也是如此。我已经在Stackoverflow和Github问题上搜索了其他问题,但没有一个建议有效。
以下是负责删除嵌入式文档的代码(使用最新的sinatra,mongo和mongoid gems):
delete '/api/items/:id/notes/:note_id' do
owner_email = session[:logged_user].email
id = params[:id]
item = ToDoItem.by_user(owner_email).find(id)
if item.nil?
halt 404, 'Item not found'
else
note_id = params[:note_id]
note = item.notes.find(note_id)
# logger.info BSON::ObjectId(note_id).to_s
# logger.info note.to_json
note.destroy
item.save!
item.reload
{ :success => true }.to_json
end
end
这是模特:
class ToDoItem
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
field :sort_order, type: Integer, default: 1
field :name, type: String
field :completed, type: Boolean, default: false
field :owner_email, type: String
field :categories, type: Array, default: ['general']
field :id, type: String
embeds_many :notes
def self.by_user(email)
where(owner_email: email)
end
def self.by_category(category)
where(categories: category)
end
def self.by_completed
where(completed: true)
end
def id
BSON::ObjectId(_id).to_s
end
end
class Note
include Mongoid::Document
include Mongoid::Timestamps
field :text, type: String
field :id, type: String
def id
BSON::ObjectId(_id).to_s
end
embedded_in :todoitem
end