mongoid标准结果不会填写所有字段

时间:2016-02-28 07:18:44

标签: ruby-on-rails mongodb mongoid

我是Rails和MongoDB以及MongoID的新手。

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  field :fbid, type: String
  field :facebookname, type: String
  field :competitorFbid, type: String
  field :createdAt, type: DateTime
  field :updatedAt, type: DateTime

  # building constructor the rails way: http://stackoverflow.com/a/3214293/474330
  def initialize(options = {})
    @fbid = options[:fbid]
    @facebookname = options[:facebookname]
    @competitorFbid = options[:competitorFbid]
  end

  def writeasjson
    hash = { :fbid => @fbid, 
      :facebookname => @facebookname, 
      :competitorFbid => @competitorFbid, 
      :createdAt => @createdAt,
      :updatedAt => @updatedAt
    }
    hash.to_json
  end

  attr_accessor :fbid, :facebookname, :competitorFbid, :createdAt, :updatedAt
end

我正在使用MongoID来查询我的mongodb数据库,如下所示:

myuser = User.where(fbid: params[:fbid]).first
render :json => myuser.writesajson

然而,结果是所有字段都是" null"

如果我打印标准结果,

render :json => myuser

它会打印所有_idauthDatabcryptPassword字段,但该字段的其余部分的值为null

以下是我在应用程序中从MongoDB数据库获得的内容。如果我从MongoHub查询,则将填充所有空值

{
    "_id": {
        "$oid": "56d2872f00af597fa584e367"
    },
    "authData": {
        "facebook": {
            "access_token": "yEf8cZCs9uTkrOq0ZCHJJtgPFxPAig9yhW6DhBCLuJqPdMZBLPu",
            "expiration_date": "2016-04-17T13:52:12.000Z",
            "id": "9192631770"
        }
    },
    "bcryptPassword": "$2a$10$9mUW3JWI51GxM1VilA",
    "competitorFbid": null,
    "createdAt": null,
    "created_at": null,
    "facebookname": null,
    "fbid": null,
    "objectId": "nLurZcAfBe",
    "runCount": 2446,
    "sessionToken": "0SwPDVDu",
    "updatedAt": null,
    "updated_at": null,
    "username": "XgcWo4iUCK"
}

我一直在调试一整天没有任何光线,任何帮助将不胜感激......

编辑: 添加回复

{"_id":{"$oid":"56d2872f00af597fa584e366"},"authData":{"facebook":{"access_token":"[ACCESS_TOKEN_REMOVED]","expiration_date":"2015-12-19T14:17:25.000Z","id":"[ID_REMOVED]"}},"bcryptPassword":"[PASSWORD_REMOVED]","competitorFbid":null,"createdAt":null,"created_at":null,"facebookname":null,"fbid":null,"objectId":"H5cEMtUzMo","runCount":790,"sessionToken":"[SESSION_TOKEN_REMOVED]","updatedAt":null,"updated_at":null,"username":"[USERNAME_REMOVED]"}

1 个答案:

答案 0 :(得分:1)

使用field方法声明数据库中的字段:

field :fbid, type: String

这也定义了使用fbid 属性fbid=fbid方法。

使用attr_accessor方法声明具有关联的访问器和mutator方法的实例变量:

attr_accessor :fbid

这也会添加fbidfbid=方法来处理基础实例变量

他们不是一回事。 Mongoid只知道field,这些是它将在数据库中使用的东西,所以你的查询工作; field还为您的字段定义了访问器和mutator方法。

但是, attr_accessor次调用之后,您有field来电,因此field创建的方法(例如fbid和{{1} } {}被fbid=创建的覆盖。结果是您的所有属性都显示为attr_accessor

解决方案是从您的课程中删除nil来电。您只需要attr_accessor来电。