2017-04-08 50 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的輸出中禁用。 –