mongoose 将前端连接到Mongodb

ve7v8dk2  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(233)

我是一个初学者,所以请放松。我已经用node.js和mongodb建立了一个数据库。我正在通过网络套接字连接接收来自物联网设备的传感器读取,并将这些条目记录到数据库中。这是我的服务器代码:

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const expressWs = require('express-ws');
const Temperature = require('./models/temperature.model');
const Humidity = require('./models/humidity.model');
const Pressure = require('./models/pressure.model');

require('dotenv').config();
// This is to create the express server and what port it will be on
const app = express();
const port = process.env.PORT || 8080;

// This is the middleware, this will allow it to parse JSON because the server will be receiving JSON
app.use(cors());
app.use(express.json());
const wsInstance = expressWs(app);
// The uri is where the database is stored, start connection to database
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true });

const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB database connection esablished successfully");
})
// Importing files
const temperatureRouter = require('./routes/temperature');
const humidityRouter = require('./routes/humidity');
const pressureRouter = require('./routes/pressure');

const router = express.Router();
// The connection to the web sockets where the sensor reads are received
app.ws('/sendData', (ws, req) => {

    ws.on('message', function incoming(message) {
        console.log(message);
        ws.broadcast(message);

        const tempData = message.slice(0, 5);
        const humidData = message.slice(6, 11);
        const pressureData = message.slice(12, 21);

        const temperature = new Temperature({
            temperature: tempData,
        });
    
        temperature.save();

        const humidity = new Humidity({
            humidity: humidData,
        });
    
        humidity.save();

        const pressure = new Pressure({
            pressure: pressureData,
        });
    
        pressure.save();
    });

    ws.broadcast = function broadcast(data) {
        wsInstance.getWss().clients.forEach(function each(client) {
            client.send(data);
        });
    };
})

app.use('/temp', temperatureRouter);
app.use('/humidity', humidityRouter);
app.use('/pressure', pressureRouter);

// This is what starts the server and listens on that port
app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

现在我尝试在我的前端检索数据以显示在一个图表中,但不明白为什么我没有收到它。这是我的前端代码:

import React, { useEffect, useState } from 'react';

function DevExpressCharts() {
    const [temperatures, setTemperatures] = useState([{
        temperature: '',
        date: ''
    }])

    useEffect(() => {
        fetch('/temperatures').then(res => {
            if(res.ok) {
                return res.json()
            }
        }).then(jsonRes => setTemperatures(jsonRes))
    })

    return (
        <div>
            <h1>hello</h1>
            {temperatures.map(temperature =>
                <div>
                    <h1>{temperature.temperature}</h1>
                </div>
                )}
        </div>
    )
}

export default DevExpressCharts;

路线:

const router = require('express').Router();
let Temperature = require('../models/temperature.model');

router.route('/temperatures').get((req, res) => {
    Temperature.find()
        .then(foundTemperature => res.json(foundTemperature))
        .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

型号:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const temperatureSchema = new Schema({
    temperature: { type: String, required: true },
}, {
    timestamps: true,
});

const Temperature = mongoose.model('Temperature', temperatureSchema);

module.exports = Temperature;

任何帮助都是非常感谢的。

rt4zxlrg

rt4zxlrg1#

您应该尝试更改此设置,并检查此设置是否能解决您的问题。

**第1点:**你是否检查过api端点是否在postman或任何其他api测试器中给出了正确的响应。
**第2点:**我注意到您正在使用.find()从数据库中查找温度集合。请尝试同样的操作:

const tempData=await Temperature.find();
if(tempData) return res.send(tempData);

**Point-3:**假设你的TemperatureRoute包含了路由器的温度。如果是这样,那么你的api应该看起来像这样:http://xyz.domain/temp/Temperature
**第4点:**您的获取API应该如下所示:

// get all collections
fetch("http://xyz.domain/temp/temperatures", {
  "method": "GET"
})
.then(response => response.json())
.then(response => {
  this.setState({
   ... //perform operations
  })
})
.catch(err => { console.log(err); 
});

我希望这能解决你的问题。

相关问题