簡體   English   中英

來自MongoDB的數據未顯示

[英]Data from MongoDB not displaying

我正在通過創建一個簡單的應用程序來學習MongoDB,該應用程序應僅顯示我設法使其與MongoShell一起使用的數據庫中的項目,但現在我想改為使用MongoDB集群,問題是我無法顯示數據根本上,我在做什么錯,如何顯示數據? 在一個名為tea的數據庫中,我的集合稱為black_tea,如您在此處看到的那樣:在嘗試使用Postman的終點時,我收到了一個空數組,因此問題出在入口點上,我如何才能正確使用端點中的數據? 在此處輸入圖片說明

這是我創建的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端點安全!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM