善意提醒:
All queries in Mongoid are Criteria, which is a chainable and lazily evaluated wrapper to a MongoDB dynamic query.
參見:http://mongoid.org/en/mongoid/docs/querying.html#query_plus
確保理解Mongoid標準懶洋洋地評估,否則會造成混亂,你和 花費你的時間和更多的時間..當我運行@result = User.find(:name =>「xxxxx」)。limit(5)時,我得到一個Mongoid :: Errors :: DocumentNotFound異常, 這是Mongoid 2.4.10 。你確定你的問題是準確的嗎?
我已將它更改爲User.where和@result = User.find(:name =>「xxxxx」)。limit(5)是一個Criteria, not(yet)從MongoDB讀取的User實例。
以下測試應該有助於明確說明,由於懶惰評估, 數據庫查詢僅在需要時發生,例如,方法to_json和方法長度之後。 此外,請尾巴您的日誌,並注意每個使用@result與to_json或長度方法 導致重複的數據庫查詢效率低下,可能不是你想要的。 您可以使用Enumerable#to_a或Enumerable#等方法強制進行評估和獲取。
測試/單位/ user_test.db
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
User.delete_all
end
test "mongoid lazy eval" do
User.create(name: 'xxxxx')
assert_equal(1, User.count)
puts "User.all.to_a: #{User.all.to_a.inspect}"
assert_raises Mongoid::Errors::DocumentNotFound do
@result = User.find(:name=>"xxxxx").limit(5)
end
puts "@result = User.find(:name=>\"xxxxx\").limit(5); @result: #{@result.inspect}"
@result = User.where(:name=>"xxxxx").limit(5)
puts "@result = User.where(:name=>\"xxxxx\").limit(5); @result.class: #{@result.class}"
puts "@result.to_json: #{@result.to_json}"
puts "@result.length: #{@result.length}"
@new_result ={:result =>@result, :count=>@result.length}
puts "@new_result: #{@new_result.inspect}"
puts "@new_result.to_json: #{@new_result.to_json}"
end
end
測試輸出
Run options: --name=test_mongoid_lazy_eval
# Running tests:
User.all.to_a: [#<User _id: 4fca03e7e4d30b1e42000001, _type: nil, name: "xxxxx">]
@result = User.find(:name=>"xxxxx").limit(5); @result: nil
@result = User.where(:name=>"xxxxx").limit(5); @result.class: Mongoid::Criteria
@result.to_json: [{"_id":"4fca03e7e4d30b1e42000001","name":"xxxxx"}]
@result.length: 1
@new_result: {:result=>#<Mongoid::Criteria
selector: {:name=>"xxxxx"},
options: {:limit=>5},
class: User,
embedded: false>
, :count=>1}
@new_result.to_json: {"result":[{"_id":"4fca03e7e4d30b1e42000001","name":"xxxxx"}],"count":1}
.
Finished tests in 0.038161s, 26.2048 tests/s, 52.4095 assertions/s.
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
這對我的作品。我看不到任何問題。 – Chamnap
我得到一個意外的輸出[{new_result:null,count:25}] –
This works length = {'count'=> @ result.length} --- @ new_result = @ result << length --- render:json =>(@ new_result).to_json() –