连接 MongoDB 到 Koa 服务器问题

发布于 2025-01-17 13:43:08 字数 2097 浏览 3 评论 0原文

我已经在我的 Koa 服务器上沉寂了一段时间了。看起来我已经很接近了,但我似乎无法完全完成它。

每当我想向消息数据库发布某些内容时,它就会崩溃并显示拓扑已关闭。

我目前正在通过邮递员添加非常基本的 json 文件,其中包含 msg 和 id 属性,希望更有经验的人可以帮助我解决这个问题。肯定会非常感激。

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} 
              

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} ????`);
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国粹 2025-01-24 13:43:08

我不完全知道您的代码问题是什么,因为它对我有用,也许与您的数据库设置有关。

我建议一个有效的例子,您可以自己尝试。

我假设您有 docker curl 在您的系统中。

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 和运行Docker组成。这将使Mongo Express在8077端口上运行,并且DB本身在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:[email protected]: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}

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:[email protected]: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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文