来自MongoDB的数据未显示

时间:2019-07-12 07:42:55

标签: javascript node.js mongodb

我正在通过创建一个简单的应用程序来学习MongoDB,该应用程序应仅显示我设法使其与MongoShell一起使用的数据库中的项目,但是现在我想改为使用MongoDB集群,问题是我无法全部显示数据,我在做什么错,如何显示数据?我的收藏集在名为tea的数据库中称为black_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>
      )
  }
}

1 个答案:

答案 0 :(得分:1)

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