2017-01-03 27 views
0

我正在嘗試使用僅僅是API應用程序的Mongodb來構建Rails後端。我有一個事件模型和API控制器,當我去到localhost:3000 /事件/ 2,我得到一個404錯誤,雖然我知道的紀錄是在我的數據庫:無法在使用Mongodb的Rails中擊中API端點

{ "_id" : 2, "name" : "String Cheese", "location" : "Durham, NC", "price" : "40.00" } 

我的控制器看起來像這樣:

class API::V1::EventsController < ApplicationController 
    respond_to :json 

    def show 
    respond_with Event.find('_id') 
    end 

    private 

    def event_params 
    params.require(:event).permit(:name, :url, :location, :dates, :price, :info, :genre, :address, :city, :tags) 
    end 
end 

我的路線是這樣的:

require 'api_constraints' 

Rails.application.routes.draw do 

    namespace :api, defaults: { format: :json }, path: '/' do 
    scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do 
     resources :users, only: [:show] 
     resources :events, only: [:show] 
    end 
    end 
end 

然後,我在我的lib文件夾中的api_constraints.rb,看起來像這樣:

class ApiConstraints 
    def initialize(options) 
    @version = options[:version] 
    @default = options[:default] 
    end 

    def matches?(req) 
    @default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}") 
    end 
end 

這是爲了消除在uri中擁有api版本號的需要。我不確定它是否影響我的終端。

所以後來當我開始我的服務器和去localhost:3000/events/2我得到一個404錯誤:

{ 「地位」:404, 「錯誤」: 「未找到」, 「異常」:「#\ u003cMongoid: :Errors :: DocumentNotFound:\ nmessage:\ n找不到具有ID(s)的類Event的文檔{\「_ id \」= \ u003e \「2 \」}。\ nsummary:\ n當調用Event時。使用id或id數組查找每個參數必須與數據庫中的文檔相匹配,否則將引發此錯誤。搜索的是id(s):{\「_ id \」= \ u003e \「2 \」}

堆棧跟蹤實際上甚至更長,所以如果有人需要它,我可以發佈整個東西。

任何幫助將不勝感激。

回答

0

我的歉意,原來原因是我通過我的終端錯誤地在mongo中存儲了新的記錄。

db.events.insert({ "_id" : 2, "name" : "Phish" })

,我應該做這樣的:我用這個錯誤地寫了一個新的條目

db.events.insert({ _id: '2', name: "Phish" })

我仍然不是很熟悉MongoDB的,但現在看來,他們保存所有的ID作爲字符串,我有一個ID保存爲一個整數,然後找不到。

+0

默認情況下,Mongoid將標識存儲爲「BSON :: ObjectId」 - 不是字符串。 https://docs.mongodb.com/ruby-driver/master/tutorials/6.0.0/mongoid-documents/ – max

1

Event.find('_id')將尋找與_id = "_id"的記錄。

您需要使用URL中的id參數。

Event.find(params[:id]) 
+0

當我改變它,我仍然有一個404錯誤: 開始GET「/ events/2」爲:: 1在2017-01-03 10:32:00 -0500 處理由Api :: V1 :: EventsController#顯示爲JSON 參數:{「id」=>「2」} MONGODB | localhost:27017 | go_loco_development.find | STARTED | {「find」=>「events」,「filter」=> {「_ id」=>「2」}} MONGODB | localhost:27017 | go_loco_development.find |成功| 0.000573s 已完成404 Not found in 2ms – LBarry

+0

@Lukas嘗試將其轉換爲Fixnum - 您在問題中包含的文檔具有id,它是一個整數,而不是字符串:'{「_id」:2 ..... '。所以像'Event.find(params [:id] .to_i)''。 – Dani

+0

我會避免手動創建ID。使用「BSON :: ObjectId」的默認方案。雖然它與簡單的數字ID相比可能看起來醜陋,但它在解決自動遞增列受競爭條件影響的複製數據庫時確實解決了一個非常實際的問題。 – max