MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Client.Close() is not a function?

https://hastebin.com/rubabogumo.cs
==> My code
(node:29533) UnhandledPromiseRejectionWarning: TypeError: client.close is not a function
I get this error if I do

const db = new KeyMongo(`mongodb+srv://CORRECT_URL.mongodb.net/test?retryWrites=true&w=majority`,{db:"mongo-test",collection:"keyv"})
db.set("KEY","VALUE").catch(console.error())

Hi @Jitesh_D,

You need to call MongoClient.connect() to establish a connection. This method either returns a promise or execute a callback. Depending on how you would like to use KeyMongo class, there are many ways to incorporate connect() in the class.

One way is have another async method to initialise KeyMongo . For example:

    async init(callback){
        this.client = new MongoClient(this.uri, {useNewUrlParser: true, useUnifiedTopology: true })
        await this.client.connect(); 
        callback.bind(this).call();
    }

    async set(key, value){
        let result = await createListing(this, key, value)
        console.log(result.insertedId);
    }
    ....

    async function createListing(obj, key, value){
        try {
            insert = await obj.client.db(obj.db).collection(obj.collection).insertOne({"_id": key,"value":value})
            return insert
        } finally {
            await obj.client.close()
        }
    }

Then you can invoke KeyMongo using:

const km = new KeyMongo(`MONGODB_URI`, {db:"dbName",collection:"collName"})
km.init(function(){
    km.set("Key","Value").catch(console.error())
});

Thank you for providing the code snippet that’s quite useful. If you have further questions, please provide which MongoDB Node.JS driver you are using.

Regards,
Wan.