Restful api不显示来自mongodb的数据

时间:2016-05-12 10:54:22

标签: json node.js mongodb rest express

我有一个非常简单的resful api,专为练习而创建。但是,当我尝试使用网址时,例如localhost:3000 /人它只会像这样 [] 来覆盖一个空数组。控制台中没有错误。我正在使用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");

的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里面有db中的数据:名为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'
}

请帮忙!!!请给我正确的方向。感谢

2 个答案:

答案 0 :(得分:2)

restful.model返回一个Mongoose模型,然后它使用复数模型名称作为集合名称。因此,在您的情况下,people模型引用peoples集合,该集合为空。 如果要正确使用mongoose命名算法,可以使用person作为模型名称。参考mongoose集合将是people,如你所愿。

更新

Mongoose naming algorithm

作为一个例子(必须安装猫鼬):

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

答案 1 :(得分:1)

在研究之后我发现问题出现在Mongoose上,它返回了复数形式的集合名称' people'作为'人民'或者' person'作为'人,这就是数据无法显示的原因。所以我只是强迫它使用我想要的集合:

var mongoose = require('mongoose');

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

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

所以我在这里添加了行{collection:' person'}来强制在我的模型中使用此集合。现在我可以根据需要从我想要的精确集合中获得结果。