【问题标题】:Mongoid as_json causes document to deleteMongoid as_json 导致文档被删除
【发布时间】:2025-11-28 00:45:01
【问题描述】:

运行以下查询时,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

广播模型

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

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

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

    field :delete, type: String
    

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

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

    【讨论】:

    • 太棒了!太棒了!哇...我不敢相信有基于字段名称的变形...
    最近更新 更多