json - Restful api 不显示来自 mongodb 的数据

标签 json node.js mongodb rest express

我有一个非常简单的 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 naming algorithm

举个例子(必须安装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/

相关文章:

node.js - 索引新文档并在同一查询中获取索引文档

node.js - Mongodb + nodejs mongoskin 更新不工作

json - 以不同的格式反序列化 JSON - Serde_JSON

javascript - 外部 JSON 和外部模板 - 无法同时工作

javascript - nvd3 无法正确计算最大 y 值

java - Firebase 实时数据库 : Howto index properly on key-value pair

mysql - 连接到 mysql 时出现错误 "connect ECONNREFUSED 127.0.0.1:3306"

node.js - "Missing credentials in config"尝试将文件流式传输到 node.js 中的 Amazon S3 存储桶时

java - mongodb 的 JDBC 驱动程序类名是什么?

java - MongoDB + Solr 性能