【问题标题】:MongoDB with Koa JS: client.connect is not a function带有 Koa JS 的 MongoDB:client.connect 不是函数
【发布时间】:2020-05-06 07:55:22
【问题描述】:

我正在尝试使用 Koa 开发我的第一个简单应用程序,它只接收一些数据并将其放入 Mongo DB 中。但是,我发现即使连接到数据库也很困难,因为我得到的响应是{"error": "this.db_client.connect is not a function"}。这是应用程序代码:

import Koa from "koa";
import bodyParser from "koa-bodyparser";

import {DBHandler} from "./db"
import {error} from "./middlewares/error";

const app = new Koa();

app.use(bodyParser());
app.use(error);

app.use(async ctx => {
    const db = new DBHandler();

    db.writeEntity(ctx.request.body);
});

app.listen(3000);

DBHandler:

export class DBHandler {
    constructor() {
        this.db_url = "mongodb://localhost:27017";
        this.db_client = new MongoClient(this.db_url, {useNewUrlParser: true, useUnifiedTopology: true});
    }

    writeEntity = (entity) => {

        console.log(this.db_client);
        this.db_client.connect((err, client) => {
            if (err) throw new Error("Connection Error");

            const db = client.db("database");
            const collection = db.collection("users");

            collection.insertOne(entity, (err, res) => {
                if (err) throw new Error("Insertion Error");

                console.log(res.ops);
                client.close;
            });
        });
    };
}

顺便说一句,console.log(this.db_client) 打印出Promise { <pending> },这意味着,我的 MongoClient 对象是一个承诺!

任何想法,正在发生什么以及如何使其发挥作用?

【问题讨论】:

  • this.db_client 引用一个新的 MongoClient 实例不应该是一个承诺。您使用的是 MongoDB 节点驱动程序here 吗?如果是,是什么版本。
  • @OTZ 我用的是 3.4.1 版
  • 你能分享一下你如何导入MongoClient类的代码sn-p吗?
  • @OTZ 只是import MongoClient from "mongodb";
  • 嗯,我明白了。这就是问题所在。我现在会发布答案。

标签: javascript node.js mongodb koa koa2


【解决方案1】:

由于您通过 cmets 确认您正在导入 MogoClient,如下所示:

import MongoClient from "mongodb";

我可以确认问题出在哪里,MongoClient 不是 mongodb 模块的直接导出,而是子导出。你应该像这样导入它:

import mongodb from "mongodb";
const MongoClient = mongodb.MongoClient;

// Or using require
const MongoClient = require("mongodb").MongoClient;

这应该可以解决问题。 您可以阅读有关使用 MongoClienthere 连接到 MongoDB 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多