2012-11-01 140 views
1

我有吐出記錄到某個網頁MongoDB的返回空數組

require 'mongo' 
require 'json' 

connection = Mongo::Connection.new 
db = connection.db("salemDB") 
db = Mongo::Connection.new.db("salemDB") 
newsCollection = db["news"] 

require 'sinatra' 
set:port, 2222 
get '/' do 
    redirect 'index.html' 
end 

get "/checkMail" do 
    newsCollection.find_one({}, {}).to_a.to_json 
end 

get "/:id" do 
newsCollection.find("_id" => params[:id]).to_a.to_json 
end 

(格式化用於閱讀的樂趣)/ checkmail輸出

[ 
    [ 
     "_id", 
     { 
     "$oid":"50880c8564a15e2631000001" 
     } 
    ], 
    [ 
     "date", 
     "2012-10-24T17:42:54+02:00" 
    ], 
    [ 
     "subject", 
     "This is a piece of news" 
    ] 
] 

/50880c8564a15e2631000001一個MongoDB的輸出此

[] 

爲什麼它不給我的對象回來?

回答

3

這是因爲ID實際上不是一個字符串或整數它是一個BSON::ObjectId,所以你必須查詢其中的一個。

這應該工作

newsCollection.find("_id" => BSON::ObjectId(params[:id])).to_a.to_json