gpt4 book ai didi

javascript - 来自 MongoDB 的数据不显示

转载 作者:行者123 更新时间:2023-12-02 23:19:38 27 4
gpt4 key购买 nike

我正在通过创建一个简单的应用程序来学习 MongoDB,该应用程序应该只显示数据库中的项目我设法让它与我的 MongoShell 一起工作,但现在我想使用 MongoDB 集群,问题是我无法完全显示数据,我做错了什么以及如何显示数据?我的收藏名为 black_tea,位于名为 tea 的数据库中,如下所示:当尝试使用 Postman 端点时,我收到一个空数组,所以问题在于入口点,如何正确使用端点中的数据? enter image description here

这是我创建的 Node.js 服务器:

// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = 4000;
const itemRoutes = express.Router();


app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb+srv://m001-student:<mongoIdentifier>.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true } )
const connection = mongoose.connection;

connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
})



itemRoutes.route('/').get( async (req, res) => {
let collection = connection.collection("black_tea");

let response = await collection.find({}).toArray();

res.send(response);
});



app.use('/items', itemRoutes);

app.listen(PORT, function() {
console.log('Server is running on' + ' ' + PORT);
})

我的前端消耗它:

export default class Blacktea extends Component {

constructor(props) {
super(props);
this.state = {
black_tea: []
};
}
blackTeaList() {
return this.state.black_tea.map(function(blackTea, i){
return <div className="tea-info-container">
<div className="tea-info" black_tea={blackTea} key={i}>
<p className="title">{blackTea.title}</p>
<img className="item-img" src={blackTea.picture} alt=""/>
<p className="description">{blackTea.description}</p>
</div>
</div>
})

}

componentDidMount() {

axios.get('http://localhost:4000/items')
.then(response => {
this.setState({black_tea: response.data})
})
.catch(function(error) {
console.log(error)
})
}

render() {
return (
<div>
{ this.blackTeaList() }
</div>
)
}
}

最佳答案

您连接到了错误的数据库。您正在连接到 test 而不是 tea:

mongoose.connect('mongodb+srv://m001-student:BaBaBa10@m001-xposu.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true } )

应该是

mongoose.connect('mongodb+srv://m001-student:BaBaBa10@m001-xposu.mongodb.net/tea?retryWrites=true&w=majority', { useNewUrlParser: true } )

更重要的是,请保护您的 mongo 端点!

关于javascript - 来自 MongoDB 的数据不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002336/

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