Mongoid as_json导致文档被删除

时间:2015-03-17 20:24:07

标签: ruby-on-rails mongodb mongoid

当运行以下查询时,MongoDB神秘地发出删除命令并删除运行as_json的对象。 to_json具有相同的效果。

Stream.first.as_json

MongoDB日志

database=integration collection=streams selector={"$query"=>{}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields=nil runtime: 62.9890ms

MOPED: 54.237.57.2:10996 DELETE       database=integration collection=streams selector={"_id"=>BSON::ObjectId('55087e6e436c611d42410000')} flags=[:remove_first]

环境

RAILS 4.2,Mongoid 4.0.2和MongoDB 3.0.0

流模型

class Stream

include Mongoid::Document

field :stream_identifier, type: String
field :cover, type: String
field :caption, type: String
field :location, type: String
field :place, type: String
field :watchers_count, type: Integer
field :comments_count, type: Integer
field :likes_count, type: Integer
field :restreams_count, type: Integer
field :activities, type: Array
field :influencers, type: Array
field :encores, type: String
field :cover_images, type: Array
field :status, type: String
field :end_time, type: Integer
field :tweet_id, type: String
field :fans, type: Array
field :likes, type: String
field :delete, type: String
field :playlist, type: String
field :restreams, type: String
field :comments, type: String
field :watchers, type: String

alias_attribute :likesCount, :likes_count
alias_attribute :coverImages, :cover_images
alias_attribute :commentsCount, :comments_count
alias_attribute :watchersCount, :watchers_count
alias_attribute :restreamsCount, :restreams_count
alias_attribute :endTime, :end_time
alias_attribute :tweetId, :tweet_id

embeds_one :broadcaster
has_one :feed

def update_stream
    UpdateStreamStatus.perform_async(self.stream_identifier)
end
end

BroadcastModel

class Broadcaster
include Mongoid::Document
field :identifier, type: String
field :name, type: String
field :display_name, type: String
field :profile, type: String
field :image, type: String

alias_attribute :displayName, :display_name

embedded_in :stream
end

1 个答案:

答案 0 :(得分:1)

您的delete中有一个名为Stream的字段:

field :delete, type: String

对于模型中的每个字段(f)(m),as_jsonto_json都会调用m.f。这意味着每次as_jsonto_json来电最终都会调用m.delete。据推测,这是调用Mongoid的delete方法并从MongoDB中删除文档(不调用回调)。

我建议您将delete字段重命名为与Mongoid方法不冲突的字段。