2016-05-12 39 views
2

我有一個非常簡單的resple api,只是爲了練習而創建的。但是,當我嘗試使用網址例如本地主機:3000 /人,它只能像這樣插入一個空數組[]。控制檯中沒有錯誤。我正在使用node-restful軟件包來創建api。這裏是我使用的代碼:Restful api不顯示mongodb的數據

Server.js(這被複制到相同從相同節點的RESTful封裝(https://github.com/baugarten/node-restful

var express = require('express'), 
    bodyParser = require('body-parser'), 
    methodOverride = require('method-override'), 
    morgan = require('morgan'), 
    restful = require('node-restful'), 
    mongoose = restful.mongoose; 
var app = express(); 

app.use(morgan('dev')); 
app.use(bodyParser.urlencoded({'extended':'true'})); 
app.use(bodyParser.json()); 
app.use(bodyParser.json({type:'application/vnd.api+json'})); 
app.use(methodOverride()); 

mongoose.connect("mongodb://localhost/mydbs"); 

var people = app.people = restful.model('people', mongoose.Schema({ 
    name: String 
    })) 
    .methods(['get', 'post', 'put', 'delete']); 

people.register(app, '/people'); 

app.listen(3000); 
console.log("working"); 

的package.json

{ 
    "name": "app1", 
    "version": "1.0.0", 
    "description": "", 
    "main": "server.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
    "author": "", 
    "license": "ISC", 
    "dependencies": { 
    "body-parser": "^1.15.1", 
    "express": "^4.13.4", 
    "lodash": "^4.12.0", 
    "method-override": "^2.3.5", 
    "mongoose": "^4.4.16", 
    "morgan": "^1.7.0", 
    "node-restful": "^0.2.5", 
    "resourcejs": "^1.2.0" 
    } 
} 

和我的mongodb的內部有數據在分貝:名爲mydbs收集:人

> show dbs 
local 0.000GB 
**mydbs 0.000GB** 
test 0.000GB 

> show collections 
people 

> db.people.find() 
{ "_id" : ObjectId("57343f28f41d55c64cca135b"), "name" : "jackal" } 

現在,當我啓動服務器,並轉到http://localhost/people它顯示一個空Array []。但它應該顯示像這樣

{ 
    _v: 0, 
_id: 123344390dfsjkjsdf, 
name: 'jackal' 
} 

請幫助JSON格式的進入!請給我正確的方向。謝謝

+0

有沒有人......誰可以回答這個問題或提示! – Sam

回答

1

確定後一個研究,我發現了問題是與貓鼬它返回多元化的形式收集名稱'人'作爲'人'或'人'作爲'人'..這就是數據不顯示的原因。所以,我只是迫使它使用我想是這樣的集合:

var mongoose = require('mongoose'); 

var PersonSchema = new mongoose.Schema({ 
    name: { 
     type: String 
    } 
}, {collection: 'person'}); 

var person = mongoose.model('person', PersonSchema); 
module.exports = person; 

所以我在這裏已經添加了一行{集合:「人」}強制使用此集合在我的模型。現在我可以根據需要從我想要的確切集合中得到結果。

2

restful.model返回一個Mongoose模型,它又使用多元化的模型名稱作爲集合名稱。所以在你的情況下,people模型引用peoples集合,這是空的。 如果您想正確使用貓鼬命名算法,可以使用person作爲型號名稱。如果您想要,參考貓鼬收藏將是people

更新

Mongoose naming algorithm

作爲一個例子(貓鼬已經被安裝到):

var utils = require('mongoose/lib/utils'); 
utils.toCollectionName('people'); // peoples 
utils.toCollectionName('person'); // people 
+0

我得到了你的觀點,感謝您的早日答覆..但我不能理解命名alogrithm ..在Mongod可以請給我一個代碼的例子,我可以使用人作爲模型名稱和人作爲集合,我不必須使用複數名稱。在此先感謝..雖然現在更改集合名稱的人民使它的工作! – Sam

+0

更新了這篇文章,爲您舉例說明「人」模型如何進入「人」收藏,「人」進入「人物」收藏。希望能幫助到你。 –