Search code examples
javascriptnode.jsmongodbkoakoa2

MongoDB with Koa JS: client.connect is not a function


I am trying to develop my first simple app using Koa, which just recieves some data and puts it in a Mongo DB. However, I found it difficult even to connect to the database, as the response I get is {"error": "this.db_client.connect is not a function"}. Here is the app code:

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);

The 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;
            });
        });
    };
}

By the way, the console.log(this.db_client) prints Promise { <pending> }, which means, my MongoClient object is a promise!

Any ideas, what is happening and how to make it work?


Solution

  • Since you confirmed via the comments that you are importing the MogoClient like this:

    import MongoClient from "mongodb";
    

    I can confirm that is where the problem is, MongoClient is not a direct export of the mongodb module, instead, it's a sub export. You are supposed to import it like this:

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

    This should fix the problem. You can read more on connecting to MongoDB with the MongoClient class here.