Home > database >  Transferring data from react js to mongodb
Transferring data from react js to mongodb

Time:06-17

I'm trying to send data from the front-end(react js) to the back-end(node js) and then to mongodb database (so it would be saved there). I called the server successfully with the data, but I'm not able to send the date to the database from the server. These are my files.

react js file: ( this function is called when the user enters some text and clicks on a button )

handleSubmit = () => {
    console.log("its running");
    let databody = {
      message: this.state.val,
    };
    console.log(" the message is :"   this.state.val);
    return fetch("http://localhost:5000/stored", {
      method: "POST",
      body: databody,
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  };

index.js - nodejs file: (Here is where I'm getting my error which says "TypeError: connectDB.collection is not a function")

const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });

const app = express();
dotenv.config();
const db = connectDB();

app.get("/", (req, res) => {
  res.send("Hey there!");
});

app.get("/Pinged", function (req, res) {
  res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});

app.use(cors({ origin: "*" }));
app.post("/stored", (req, res) => {
  console.log("its running 2: "   req.body);
  db.collection().insertOne(req.body, (err, data) => {
    if (err) return console.log(err);
    res.send("saved to db: "   data);
  });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

db.js file inside config folder:

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    });
    console.log(`MongoDB Connected : ${conn.connection.host}`);

    return conn;
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};

module.exports = connectDB;

CodePudding user response:

Here, in db.js you should return conn.connection

  const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    })
    console.log(`MongoDB Connected : ${conn.connection.host}`)
    return conn.connection
  } catch (err) {
    console.error(err.message)
    process.exit(1)
  }
}
  • Related