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

235
Visualizações
Connecting MongoDB to Koa Server Issues

I have been stuck on my Koa server for quiet a while now. It seems like I'm very close, I just can't seem to fully finish it.

Whenever I want to post something to my messages DB, it crashes and says Topology is closed.

I'm currently adding very basic json files through postman with a msg and id property, hope someone more experienced can help me iron this out. Would definitely be much appreciated.

const Koa = require("koa");
const bodyparser = require("koa-bodyparser");
const KoaRouter = require("koa-router");
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017/';

const app = new Koa();
const router = new KoaRouter();
const client = new MongoClient(url);
const db = client.db('serverTesting');
const messages = db.collection("messsages")

const PORT = 3002;

app.use(bodyparser())

// router

app.use(router.routes());

router.get("/", ctx => {
    ctx.body = "Hello, this is the Homepage.";
});

router.get("/test", ctx => {
    ctx.body = { msg: "Hello Test"};
});

router.post("/test", ctx => {
    const message = ctx.request.body;
    messages.insertOne(message);
    ctx.body = "Message was updated."
    console.log("Added message to database: ")
    console.log(messages);
});

router.delete("/test", ctx => {
    const msg = ctx.request.body.msg;
    const deleted = messages.find(message => message.msg === msg);
    if (deleted) {
        messages = messages.filter(message => message.msg !== msg);
        console.log("Deleted message from database: ")
        console.log(messages)
        ctx.body = "Message was deleted."

    } else {
        ctx.body = "This message was not found in the database"
    }
})

router.put("/test", ctx => {
    const id = ctx.request.body.id;
    const deleted = messages.find(message => message.id === id);
    if (deleted) {
        messages.forEach(message => {
            if (message.id === id) {
                message.msg = ctx.request.body.msg
            }
        })
        console.log("Updated message in database: ")
        console.log(messages)
        ctx.body = "Message was updated."
    } else {
        ctx.body = "This message was not found in the database"
    }
})

app.listen(PORT, () => {
    client.connect()
    console.log(`Server running on http://localhost:${PORT} 🚀`);
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't exactly know what the issue is with your code because it worked for me, perhaps it has something to do with your DB setup.

I'm suggesting a working example and you can try it on your own.

I assume you have Docker and Curl in your system.

docker-compose.yaml

version: '3.1'
services:
  mongo:
    image: mongo
    restart: always
    ports:
      - "27077:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - "8077:8081"
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/

Create docker-compose.yaml and run docker compose up. This will make Mongo express running on 8077 port and the DB itself on 27077.

index.js

const Koa = require("koa");
const bodyparser = require("koa-bodyparser");
const KoaRouter = require("koa-router");
const { MongoClient } = require("mongodb");

(async () => {
  const PORT = 3002;
  const url = "mongodb://root:example@127.0.0.1:27077/";

  const client = await new MongoClient(url).connect();
  const db = client.db("my-database");
  const messages = db.collection("messages");

  const app = new Koa();
  const router = new KoaRouter();

  app.use(bodyparser());
  app.use(router.routes());

  router.post("/create", async (ctx) => {
    const message = ctx.request.body;
    await messages.insertOne(message);
    ctx.body = "DB record created";
  });

  app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server running on http://127.0.0.1:${PORT} 🚀`);
  });
})();

Run the server with node index.js and send the payload to test it

curl --location --request POST 'http://localhost:3002/create' \
--header 'Content-Type: application/json' \
--data-raw '{
    "message": "hello there",
    "data": "This is me!"
}'

You can navigate to http://localhost:8077/ and check the created value.

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