1

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.

Data as shown by Robo3T

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;
6
  • What do you get when you console.log(this.state.questions) in your render? Try doing it before your if statement, you should see it twice Commented Dec 2, 2017 at 18:33
  • where is this.props.url coming from Commented Dec 2, 2017 at 18:34
  • @BravoZulu Yes I see two console.logs. One undefined and data after the fetch request completes. Commented Dec 2, 2017 at 18:38
  • @Aaqib props.url is coming from index.js. Commented Dec 2, 2017 at 18:38
  • ok, what do you see? Commented Dec 2, 2017 at 18:38

1 Answer 1

4

What is the name of the collection in mongo db? Is it questions? By default, when you don't provide a collection name while defining the schema, mongoose will pluralize the schema name, in your case Question. You can override this behavior using var schema = new Schema({..}, { collection: 'question' });

Sign up to request clarification or add additional context in comments.

1 Comment

The name of the collection in Mongodb is 'questions'. Also I tried adding {collection: 'question'} and now I get a completely empty array. I think its because mongoose has created a new collection named 'question' in mongodb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.