我有一个非常简单的 resful api,只是为了练习而创建的。但是当我尝试使用 url 例如localhost:3000/people 它只显示像这样的空数组 [ ]。控制台没有错误。我正在使用 node-restful 包来创建 api。这是我使用的代码:
Server.js(这是从 node-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");
包.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 中有数据在 db:named mydbs Collection:people
> 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 时它显示一个空数组 [ ]。但它应该以 Json 格式这样的方式显示条目
{
_v: 0,
_id: 123344390dfsjkjsdf,
name: 'jackal'
}
求助!!!请给我正确的方向。谢谢
最佳答案
restful.model
返回一个 Mongoose 模型,它又使用复数模型名称作为集合名称。所以在你的例子中,people
模型引用了 peoples
集合,它是空的。
如果想正确使用mongoose命名算法,可以使用person
作为模型名。引用的 mongoose 集合将是 people
,如您所愿。
更新
举个例子(必须安装mongoose):
var utils = require('mongoose/lib/utils');
utils.toCollectionName('people'); // peoples
utils.toCollectionName('person'); // people
关于json - Restful api 不显示来自 mongodb 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37184836/