API 在 MongoDB 中存在数据时返回空数组
Posted
技术标签:
【中文标题】API 在 MongoDB 中存在数据时返回空数组【英文标题】:API returning Empty Array while data is present in MongoDB 【发布时间】:2018-05-16 14:22:08 【问题描述】:所有。我是一个初学者,正在尝试使用 Express 后端构建一个 React 应用程序。我已经构建了一个从 MongoDB 获取数据的 API。这是 Robo3T 显示的 MongoDB 中的数据。我的问题是数据包含似乎在 MongoDB 中显示数据的选项数组(使用 Robo3T),但选项数组在 API 响应中为空。
Data as shown by Robo3T
API 响应如下:
[
_id: "5a21536a70ef53552d30e709",
q_text: " ¿Cuál es tu edad, sexo y lugar de nacimiento?",
options: [ ]
,
_id: "5a21536a70ef53552d30e70a",
q_text: "¿Actualmente asistes a la escuela?",
options: [ ]
,
_id: "5a21536a70ef53552d30e70b",
q_text: "¿Cuál es tu grado de estudios? (grado y programa)",
options: [ ]
]
Server.js
//importing all dependencies
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Question = require('./models/Question');
//Connecting to MongoDB server
mongoose.connect('mongodb://localhost/local', useMongoClient: true);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));
//Creating our Express App Instance
var app = express();
var router = express.Router();
//Specifying the port number
var port = process.env.PORT || 3001;
//Configuring body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded(extended: true));
//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next)
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
);
router.get('/', function(req, res)
res.json(message : 'API initialized');
)
router.route('/questions')
//retrieve all questions from database
.get(function(req, res)
Question.find(, function(err, questions)
if(err)
res.status(500).send(error: 'Could not fetch Questions');
else
res.json(questions);
)
)
app.use('/api', router);
//start the server and listen for requests
app.listen(port, function()
console.log(`Server listening on port $port`);
)
models/Question.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var question = new Schema(
q_text:String,
options:[
type: String,
o_text: String
]
);
module.exports = mongoose.model('Question',question);
从 ./components/App.jsx 访问数据
import React, Component from 'react';
import axios from 'axios';
import Question from './Question';
class App extends Component
constructor(props)
super(props);
this.state =
dataLoaded: false,
questions: []
;
this.loadQuestions = this.loadQuestions.bind(this);
loadQuestions()
axios.get(this.props.url)
.then(res =>
this.setState(questions: res.data);
this.setState(dataLoaded: true)
)
componentDidMount()
this.loadQuestions();
render()
if(this.state.dataLoaded)
console.log(this.state.questions[2].options);
return(
<div>
<Question text=this.state.questions[1].q_text/>
</div>
)
else
return(
<div>Loading...</div>
);
export default App;
【问题讨论】:
console.log(this.state.questions)
在渲染中得到什么?尝试在您的 if
声明之前执行此操作,您应该会看到两次
this.props.url
来自哪里
@BravoZulu 是的,我看到了两个 console.log。获取请求完成后一个未定义和数据。
@Aaqib props.url 来自 index.js。
好的,你看到了什么?
【参考方案1】:
mongo db 中的集合名称是什么?是问题吗?默认情况下,当您在定义架构时不提供集合名称时,猫鼬会将架构名称复数,在您的情况下为 Question.您可以使用覆盖此行为 var schema = new Schema(.., collection: 'question' );
【讨论】:
Mongodb 中集合的名称是'questions'。我也尝试添加 collection: 'question' ,现在我得到一个完全空的数组。我认为这是因为 mongoose 在 mongodb 中创建了一个名为“question”的新集合。以上是关于API 在 MongoDB 中存在数据时返回空数组的主要内容,如果未能解决你的问题,请参考以下文章
MongoDB Lookup 返回一个空数组,只有在没有数据的时候
MongoDB Lookup 返回一个空数组,只有在没有数据的时候