Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Promises don't have collection method

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
    });
  });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda