Is there a way to wrap the mongodb drivers to add extra functionality?

As the title says, I want to add extra methods to the mongodb drivers.
Currently i’m using a collection instance to to insert, delete documents in my database like this:

// collName.js
const client = new MongoClient(uri);
const db = client.db("dbName");
export default const collection = db.collection("collName");
import collection form "collName.js"

cont data = [ ]

But I would like to add some methods to the collection instance, to do something like this:


I guess, I could create my own class:

class myCollection {
  col = db.collection("collName");
  function modifiedInsertMany(data) {
    // do stuff with data
    return col.insertMany(data);

But if i did that I would have to rewrite every single method of the original mongodb.Collection, isn’t that correct?
If possible, I want to keep all the methods of the mongodb.Collection and just add a couple of my methods.

Is it possible to do that?

1 Like

Not a dev but if Collection were a Class you can extend a class, adding new methods. For example:

class myColl extends Collection{
constructor(name1, arg2,arg3){
  super(name); //calls 
 //uses methods like find below 
  this.myFind = function (arg2) { return this.find(...) }

But from you code it is just an object not a class, but you can still add collection.mymethod= function (){ }.

Doesn’t writing a wrapper fits your needs though?

function myFind(coll, ...args){
//or whatever

I thought doing that but how do I call super() in my class constructor?
This is written in the mongodb docs:

The Collection class is an internal class that embodies a MongoDB collection allowing for insert/update/remove/find and other command operation on that MongoDB collection.
COLLECTION Cannot directly be instantiated. link

When you do

// collName.js
const client = new MongoClient(uri);
const db = client.db("dbName");

Indeed it appears to be a collection instance probably called under the hood.

But I do not think you can modify a class definition unless you add it to MongoDB code itself, and extending won’t be useful here. You can, I think, modify the prototype of the class:

> Array.prototype.myFn = function() { console.log(this) }
[Function (anonymous)]
> a = new Array(1,2,3)
[ 1, 2, 3 ]
> a.myFn()
[ 1, 2, 3 ]

Just add the functions to the Collection.prototype

But I would just write wrapper functions as I said before.