Viktor Justo Viktor Justo - 2 months ago 10
Ruby Question

Mongoid::Criteria.only(:name) returns all fields nil except name

When I run

User.only(:name).all
or whatever variant of that query, I get:

[#<User _id: 52003fb8487874985b
000003, created_at: nil, updated_at: nil, role_ids: nil, name: "Tom Amfeagfhbdge Bowersman", usernam
e: nil, fb_id: nil, fb_token: nil, email: nil, encrypted_password: nil, reset_password_token: nil, r
eset_password_sent_at: nil, remember_created_at: nil, sign_in_count: nil, current_sign_in_at: nil, l
ast_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>,
#<User _id: 5200405a487874fb550
00004, created_at: nil, updated_at: nil, role_ids: nil, name: "Carol Amfdheibbjbf Sadanwitz", userna
me: nil, fb_id: nil, fb_token: nil, email: nil, encrypted_password: nil, reset_password_token: nil,
reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: nil, current_sign_in_at: nil,
last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>,
#<User _id: 520040d14878746fe5
000005, created_at: nil, updated_at: nil, role_ids: nil, name: "Tom Amfdidheeidd Yangson", username:
nil, fb_id: nil, fb_token: nil, email: nil, encrypted_password: nil, reset_password_token: nil, res
et_password_sent_at: nil, remember_created_at: nil, sign_in_count: nil, current_sign_in_at: nil, las
t_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>]


All the fields in my document return with a nil value except the parameter for the only function.

I want to get the result something kind of like this:

"data": [
{
"id": "5008484"
},
{
"id": "47402727"
},
{
"id": "500154435"
},
{
"id": "500598450"
},
{
"id": "500655911"
},
{
"id": "500666528"
},
{
"id": "500700148"
},
{
"id": "500973616"
},
{
"id": "501130485"
},
{
"id": "501254060"
}]


Instead of "id", "name"

Answer

The only way i have found so far is using the Mongo driver directly.

Mongo::MongoClient.new(ENV['MONGOID_HOST'], ENV['MONGOID_PORT']).db(ENV['MONGOID_DATABASE']).collection('friends').find({}, {fb_id: 1})

Comments