【问题标题】:Rest api GET call doesn't return any value from the mongoDBRest api GET 调用不从 mongoDB 返回任何值
【发布时间】:2017-07-10 09:53:58
【问题描述】:

我正在尝试使用以下代码在我的 mongoDB 本地数据库中对我的流派进行 GET 请求:

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
Genre = require('./models/genre.js');
Application = require('./models/apps.js');

// Connect to Mongoose
mongoose.createConnection('mongodb://localhost/appstore');
var db = mongoose.connection;

// Root Call
app.get('/', function(request, response) {
  response.send('Please use /api/apps or /api/genres/');
});

// Get genres
app.get('/api/genres', function(request, response) {
  Genre.getGenres(function(error, genres){
    if(error){
      throw error;
    }
    response.json(genres);
  });
});

// Get apps
app.get('/api/apps', function(request, response) {
  Application.getApplications(function(error, apps){
    if(error){
      throw error;
    }
    response.json(apps);
  });
});


app.listen(28017);
console.log('Running on port 28017...');

在这个文件中,我正在创建一个函数来搜索我们 mongoDB 中的所有流派。不幸的是,它没有这样做并返回我:

localhost 没有发送任何数据。 有时只是空行。

很奇怪,它确实适用于根调用 (/) 并且会输出:

请使用 /api/apps 或 /api/genres/

genre.js

var mongoose = require('mongoose');

// Genre Schema
var genreSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  create_date: {
    type: Date,
    default: Date.now
  }
});

// this is now accessible from anywhere else
var Genre = module.exports = mongoose.model('genre', genreSchema);

// Get Genres
module.exports.getGenres = function(callback, limit){
  Genre.find(callback).limit(limit);
}

我非常感谢任何帮助,因为这是我尝试构建的第一个简单的 REST api。提前致谢!

【问题讨论】:

    标签: node.js mongodb rest express mongoose


    【解决方案1】:

    解决方案显然是使用了一个已弃用的函数:

    mongoose.connect('mongodb://localhost/appstore');

    代替:

    mongoose.createConnection('mongodb://localhost:27017/appstore');

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 2017-11-26
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2015-07-18
      • 2021-08-17
      相关资源
      最近更新 更多