32

I have set up a rails3+mongoid application and when I open the rails console, none of the finders seem to work - http://d.pr/FNzC

User.all
User.find(:all, :conditions => { first_name => "John" })

both return:

#<Mongoid::Criteria
  selector: {},
  options:  {}>

Am I doing something wrong?

Hutch
  • 841
  • 1
  • 8
  • 9

3 Answers3

59

Okay, so this is part of what makes mongoid irritating for newcomers. People expect methods like User.all to actually return an array when it really just returns the Criteria object.

In order to provide the syntatic sugar of chainable methods and other fancy query mechanisms, Mongoid seems to use a lazy loading type thing.

You can do:

#array index
User.all[0]

#first/last
User.all.first

#each over things, print out all the users
User.all.each {|u| p u}

#edit, I forgot to include this, which is probably what you really want
#this spits out an array
User.all.to_a

It makes it difficult to quickly verify that things are working for newcomers from ActiveRecord where User.all just returns an array.

voxobscuro
  • 2,132
  • 1
  • 21
  • 45
  • 2
    Definitely. Though they have documentation, it didn't seem to suggest that the pointers actually created criteria objects that you have to iterate over. As you said, slightly irritating for newcomers used to the AR classes. – Hutch Jan 27 '11 at 03:08
  • What if you get a connection error when using `.to_a`? – Gcap Oct 13 '15 at 20:19
1

Try this:

    User.all.first        
    User.find(:first, :conditions => {:first_name => 'John'})    
    User.where(:first_name => 'John').first
kriysna
  • 6,118
  • 7
  • 30
  • 30
1

this works perfectly..

 User.all.entries
ELTA
  • 1,474
  • 2
  • 12
  • 25