【问题标题】:Mongoose returns empty JSON arrayMongoose 返回空 JSON 数组
【发布时间】:2018-09-26 18:23:29
【问题描述】:

Mongoose、express、MongoDB 返回一个空的 json 数组 -- []。

我该如何解决这个问题?

已安装所有软件包。已经使用 Robo 3t 将数据输入 MongoDB,所以我认为问题在于 mongoose 没有以正确的方式从 MongoDB 请求数据。

server.js:这是在 /app 文件夹中

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';

import Issue from './models/issue.js';

const app = express();
const router = express.Router();

app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/issues');

const connection = mongoose.connection;

connection.once('open', () => {
    console.log('MongoDB database connection established successfully!');
});

router.get("/issues", function(req, res) {
    Issue.find({})
    .exec(function (err, issues) {
        if (err)
            console.log(err);
        else
            console.log("successfully requested");
            res.json(issues);
    });
});

Index.js:位于 /app/models 文件夹中

import mongoose from 'mongoose';

const issueSchema = new mongoose.Schema({
    title: {
        type: String
    },
    responsible: {
        type: String
    },
    description: {
        type: String
    },
    severity: {
        type: String
    },
    status: {
        type: String,
        default: 'Open'
    }
});

module.exports = mongoose.model('Issue', issueSchema, 'Issues');

【问题讨论】:

  • 来自 robo3T 可以检查并更新我的问题集合名称吗?
  • 这是“问题”问题仍未解决。
  • 检查我的答案它对我有用我运行了你的代码

标签: node.js mongodb express mongoose


【解决方案1】:

router 更改为app 如下所示,并确保您的集合名称在数据库中为Issues别忘了重启你的服务器

app.get("/issues", function(req, res) {
    Issue.find({})
    .exec(function (err, issues) {
        if (err)
            console.log(err);
        else
            console.log("successfully requested");
            res.json(issues);
    });
});

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2015-08-16
    • 2017-09-12
    • 1970-01-01
    • 2016-12-04
    • 2019-04-27
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多