2017-04-08 49 views
0

我有一个模型,返回JSON:如何使用mongoid

class Client 
    include Mongoid::Document 
    field :name, type: String 
    field :age, type: Integer 
    index({ name: 1 }, { unique: true }) 

    def self.list 
    self.all.as_json 
    end 
end 

当我打电话Client.list我得到如下:

[{"client"=>{"_id"=>{"$oid"=>"58e91ccb9509d36cbaa8c79b"}, "name"=>"mark", "age"=>30}}] 

我什么后:

[{"_id"=>{"$oid"=>"58e91ccb9509d36cbaa8c79b"}, "name"=>"mark", "age"=>30}] 
+0

我有同样的问题,所以我写了一个关于我如何解决它的博客。你可能会发现它很有帮助。 https://medium.com/aviabird/mongoid-how-to-serialize-to-json-with-a-string-id-attribute-2d5c1bc284a7 – VoidZero

+0

@VoidZero这是不一样的问题:) –

回答

0

您正在使用哪个版本的mongoid?

检查的文档: https://docs.mongodb.com/ruby-driver/master/tutorials/6.1.0/mongoid-installation/

您可以禁用include_root_in_json去除输出JSON的型号名称。

你可以试试这个解决方案吗?

+0

使用mongo 2.4.1 ,使用mongoid 6.1.0,使用bson 4.2.1。问题是默认情况下,mongoid在结果中返回类名。这不是数据库中的数据看起来像 –

+0

我认为我不明白你的观点,但你阅读我发送的链接?类名可以在json的输出中禁用。 –