all. I am a beginner and trying to build a React app with a Express backend. I have built an API that gets data from MongoDB. Here's the data inside MongoDB as shown by Robo3T. My question is that the data contains options array that seems to show data in the MongoDB (using Robo3T) but the options array is empty in the API response.
The API response is as follows:
[
{
_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);
Accessing the data from ./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)in your render? Try doing it before yourifstatement, you should see it twicethis.props.urlcoming from