Im trying to use the collection method but it seems like i cant really use it as db.collection since db is calling connectDB and connectDB is actually a promise that returns conn which is my mongoURI. My question is what could I use to be able to call the collection method with my mongoURI to send the data from the front-end to the database?.
this is my db.js file
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;
index.js (where im using the collection method):
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}!`));
There might be some errors in the code since I dont work on the back-end side too often so please let me know if there are any.
If you're using a recent enough version of Node.js which supports top-level await, then simply await the async function call:
const db = await connectDB();
Alternatively, if you can't use top-level await, you can resolve the Promise when you need to. For example:
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.then(conn => {
conn.collection().insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
});
I'm not 100% sure about handling these connections, and another option could be to remove the top-level call to connectDB() entirely and invoke it on each request:
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
connectDB().then(db => {
db.collection().insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
});