首页 > 解决方案 > Data from MongoDB not displaying

问题描述

I am learning MongoDB by creating a simple app that should just display items from the database I managed to get it working with my MongoShell, but now I want to use the MongoDB Cluster instead, the problem is that I am not able to display the data at all, what am I doing wrong and how can I display the data? My collection is called black_tea inside a database called tea as you can see here: When trying the end point with Postman I recieve an empty array, so the problem is with the entry point, how can I consume the data from my endpoint properly? enter image description here

Here is my node.js server that I created:

// 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);
})

And my front end that consumes it:

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>
      )
  }
}

标签: javascriptnode.jsmongodb

解决方案


您正在连接到错误的数据库。您正在连接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 端点!


推荐阅读