【问题标题】:Why I get only [] in web page from res.json() in express为什么我在 express 中从 res.json() 只得到网页中的 []
【发布时间】:2017-07-04 10:53:01
【问题描述】:

所以,当我尝试在浏览器中显示 json 数据时,我只会得到 [] 而不是完整数据。 我正在尝试使用 mongoose 和 express 显示来自 mongodb 的数据。我在数据库中有一个集合和一个我试图显示的文档,但我只得到 []。为什么?这是代码: app.js:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Person = require('./Person.model');

const app = express();

mongoose.Promise = global.Promise;
const db = 'mongodb://localhost/project';
mongoose.connect(db);
mongoose.connection.once('open', () => console.log('connection has been made...')).
on('error', (error) => console.log(error));

app.get('/', function(req, res) {
    res.send('It is good to be here');
});

app.get('/persons', function(req, res) {
    Person.find({}).exec(function(error, persons) {
        if (error) {
            res.send(error);
        } else {
            res.json(persons);
        }
    });
});

app.listen(3000, () => console.log('now listening to port 3000'));

和 Person.model.js :

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PersonSchema = new Schema({
    name: String,
    age: Number,
    favcolor: String,
    osobina: String
});

const Person = mongoose.model('person', PersonSchema);

module.exports = Person;

【问题讨论】:

  • 你的数据库里确实有数据,对吧?

标签: json mongodb express mongoose


【解决方案1】:

因为您使用的是 Promise 和 Mongoose,您可以尝试更改您的代码,而不是像这样使用回调函数

app.get('/persons', function(req, res) {
  Person.find({}).exec().then(function(persons) {
    res.json(person);
  }).catch(function(error) {
    res.send(error); //Will lead to a 200 with the error message inside
  });
});

编辑

定义模型时不应使用new。我已经从您的模型中删除了一些冗余代码,这是有效的:

const mongoose = require('mongoose');

const PersonSchema = mongoose.Schema({
    name: String,
    age: Number,
    favcolor: String,
    osobina: String
});

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

【讨论】:

  • 我在浏览器中仍然只得到 [] 而没有 json 数据。我尝试使用其他数据库和集合,但总是得到相同的结果。在 mongo shell 中一切正常,没有错误。
  • 复制你的代码,发现错误,只需从模型声明中删除new
  • 还是不行。我只得到[]。考虑到 new 这不是错误link。我重新启动了 mongo,尝试了所有代码组合,检查了 mongo shell,但我仍然没有得到 json 数据。
  • 好吧.. 我复制了你的代码。删除了new,它在这里工作..对不起,伙计
  • 不。不起作用:(。即使Person.count()现在给我0。谢谢你的尝试。
猜你喜欢
  • 2010-12-19
  • 1970-01-01
  • 2013-11-26
  • 2019-08-24
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
相关资源
最近更新 更多