gpt4 book ai didi

node.js - 当 MongoDB 中存在数据时 API 返回空数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:14:54 24 4
gpt4 key购买 nike

全部。我是一个初学者,正在尝试构建一个带有 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;

最佳答案

mongo db 中的集合的名称是什么?是疑问句吗?默认情况下,当您在定义架构时不提供集合名称时, Mongoose 会将架构名称复数化,在您的情况下是问题。您可以使用以下方法覆盖此行为var schema = new Schema({..}, { collection: '问题' });

关于node.js - 当 MongoDB 中存在数据时 API 返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com