MongoDB返回空数组

时间:2012-11-01 21:04:38

标签: ruby mongodb sinatra

我有一个将记录吐到网页上的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输出

[]

为什么它不会让我的对象回来?

1 个答案:

答案 0 :(得分:3)

那是因为id实际上不是字符串或者Integer是BSON::ObjectId,所以你必须查询其中一个。

这应该有效

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