在MongoDB中存在数据的同时返回空数组的API
全部。我是一名初学者,并试图用Express后端构建一个React应用程序。我已经构建了一个从MongoDB获取数据的API。这里是Robo3T所示的MongoDB内部的数据。我的问题是,数据包含选项数组,似乎在MongoDB中显示数据(使用Robo3T),但选项数组在API响应中为空。在MongoDB中存在数据的同时返回空数组的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}`);
})
模型/ 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;
回答:
什么是蒙戈分贝集合的名称访问数据?这是问题吗?默认情况下,如果在定义模式时没有提供集合名称,如果您没有提供集合名称,mongoose会复制模式名称,在您的案例问题中。您可以使用 覆盖此行为var schema = new Schema({..},{collection:'question'});
以上是 在MongoDB中存在数据的同时返回空数组的API 的全部内容, 来源链接: utcz.com/qa/257640.html