Home > front end >  Storing Data into MongoDB is failing
Storing Data into MongoDB is failing

Time:11-20

I am new to the MERN stack and I want to store user information into the MongoDB which has two string attributes "name" and "role".

I am getting an error in the browser console which states "Failed to load resource: Request timeout" and "Unhandled Promise Rejection: AxiosError: timeout exceeded"

server index.js

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors"); 
app = express();

const bookModel = require("./models/book");
const userModel = require("./models/user"); 

app.use(express.json());
app.use(cors);  

// mongoose.connect('mongodb://mh_user:<credentials>').then(() => {console.log('test')});

mongoose.connect("mongodb://mh_user:<credentials>", {
    useNewUrlParser: true,
})

// usermodel

app.postUser("/insert", async (req, res) => {

    const userName = req.body.userName
    const role = req.body.role
    const user = new userModel({ username: userName, role: role })

    try {
        await userModel.save();
    } catch (err) {
        console.log(err);
    }
});

app.getUser("/read", async (req, res) => {
    userModel.find({}, (err, result) => {
        if(err) {
            res.send(err)
        } 
        res.send(result)
    })
});


// bookmodel
app.post("/insert", async (req, res) => {

    const bookName = req.body.bookName
    const ISBN = req.body.ISBN
    const book = new bookModel({ bookname: bookName, ISBN: ISBN })

    try {
        await bookModel.save();
    } catch (err) {
        console.log(err);
    }
});

app.get("/read", async (req, res) => {
    bookModel.find({}, (err, result) => {
        if(err) {
            res.send(err)
        } 
        res.send(result)
    })
});

app.listen(3001, () => {
    console.log("Server running on port 3001 ...");
})

client adduser.js

import styles from './Home.module.css'
import React, { useState } from "react";
import Axios from "axios"

export default function AddUser() {
    const [userName, setUserName] = useState("");
    const [role, setRole] = useState("");

    const addToDatabase = () => {
        Axios.post("http://localhost:3001/insert", { userName: userName, role: role })
    }

    return (
        <div className={styles.container}>

            <main className={styles.main}>
                <h1 className={styles.title}>
                    Fügen Sie einen <a>neuen Nutzer</a> hinzu
                </h1>

                <p className={styles.description}>
                    Create - Operation{' '}
                </p>

                <div className={styles.grid}>
                    <form className={styles.table}>
                        <label>
                            <input
                                onChange={(event) => {
                                    setUserName(event.target.value);
                                }}
                                type="name" placeholder='name'
                            />
                        </label>
                        <label>
                            <input
                                onChange={(event) => {
                                    setRole(event.target.value);
                                }}
                                type="role" placeholder='role'
                            />
                        </label>
                    </form>
                </div>
                <br></br>
                <button
                    onClick={addToDatabase}
                >speichern</button>
                <br></br>
                <a href="http://localhost:3000/">
                    <button>Hauptmenü</button>
                </a>
            </main>

            <footer className={styles.footer}>
                <a>
                    Powered by{' '}- Gruppe 1
                </a>
            </footer>

        </div>
    );
}

server user.js

const mongoose = require('mongoose'); 

const userSchema = new mongoose.Schema({
    name: {
        type: String, 
        required: true,
    }, 
    role: {
        type: String, 
        required: true,
    }
}); 

const user = mongoose.model('userData', userSchema)
module.exports = user

CodePudding user response:

There are many mistakes in your code :

server index.js

app.use(cors) 

Replace it by :

app.use(cors()) 

Also

app =express()

Replace it by

const app= express(); 

Also

app.postUser and app.getUser is not available on express middleware.
app.use and app.post are the ones.

CodePudding user response:

The problem is that your app is trying to load a library called Axios and is not finding it.

  1. Make sure Axios library is installed in your app / package.json / dependencies and been called inside your project.

  2. Make sure the version of the Axios library you are using works with the node.js and express versions you are implementing.

  3. Handle the exception property. Seems is not been handle the right way.

  4. Try inserting data manually from postman using you /insert endpoint. It will help to know if database connection is working property. If so, then the issue is with the library.

  • Related