tweakin_rican
tweakin_rican

Reputation: 1

Connecting front end to Mongodb

I am a beginner in coding, so please take it easy. I have built a database with node.js and mongodb. I am receiving sensor reads from an IoT device through a web sockets connection and am logging those entries to the database. This is my server code:

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

Now I am trying to retrieve that data in my front end to display in a graph but do not understand why I am not receiving it. This is my front end code:

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;

Routes:

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;

Models:

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;

Any help is greatly appreciated.

Upvotes: 0

Views: 193

Answers (1)

user20182014
user20182014

Reputation:

You should try changing this and check if this solves your problem or not.

Point-1: Did u check if the api endpoint is giving proper responses in postman or any other api tester.

Point-2: I noticed you are finding temperature collections from the database using .find(). Try doing it likewise:

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

Point-3: Assuming your TemperatureRoute contains the router of the temperature. If so, then your api should look like this: http://xyz.domain/temp/Temperature

Point-4: Your fetch api should like this:

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

I hope this solves your problem..

Upvotes: 0

Related Questions