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

问题描述 投票:0回答:1

我是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]"}
ruby-on-rails mongodb mongoid
1个回答
1
投票

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

field :fbid, type: String

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

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

attr_accessor :fbid

这也将添加fbidfbid=方法来处理底层实例变量。

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

但是你的attr_accessor调用后你有一个field调用,所以field创建的方法(如fbidfbid=)被attr_accessor创建的方法覆盖。结果是所有属性都显示为nil

解决方案是从你的班级中删除attr_accessor电话。你只需要field电话。

© www.soinside.com 2019 - 2024. All rights reserved.