0

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;
3
  • "I'm getting my error which says" - pleas don't re-tell the error with own words. Copy-paste, ideally with the stake trace. const connectDB = async () => says connectDB is a Promise. Promises don't have collection method. You need at least to await it resolved. Commented Jun 15, 2022 at 13:25
  • My bad I will edit my question. So what you are saying is that i ndde to delete asyn so it would accept the methos collection?. Also, I would really appreciate it if you can let me know if im doing any other errors anywhere. Commented Jun 15, 2022 at 13:31
  • 1
    if you delete async you won't be able to await mongoose.connect inside. I'd recommend to do university.mongodb.com/courses/M220JS/about it's only 6 hrs, but it will save you days in the first month alone. Commented Jun 15, 2022 at 14:03

1 Answer 1

1

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)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.