I am trying to use the following class db.js
to operate mongodb
'use strict'
const { MongoClient } = require('mongodb');
const API = {
db: {
db_url: 'mongodb://127.0.0.1:27017',
db_test: {
db_name: 'test'
}
}
};
class Db {
dbClient = null;
dbUrl;
dbName;
static getInstance(dbUrl, dbName) {
if (!Db.instance) {
Db.instance = new Db(dbUrl, dbName);
}
return Db.instance;
}
constructor(dbUrl, dbName) {
this.dbUrl = dbUrl;
this.dbName = dbName;
this.connect();
}
connect() {
return new Promise((resolve, reject) => {
if (this.dbClient) {
resolve(this.dbClient);
}
MongoClient.connect(this.dbUrl, {useUnifiedTopology: true}, (err, connectedClient) => {
if (err) {
reject(err);
}
this.dbClient = connectedClient.db(this.dbName);
resolve(this.dbClient);
});
});
}
find(tablename, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const result = db.collection(tablename).find(json);
result.toArray((err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
})
.catch(err => {
reject(err);
});
});
}
}
module.exports = Db.getInstance(API.db.db_url, API.db.db_test.db_name);
But I always get an error when it runs, it gives
/home/admin/depis/node_modules/mongodb/lib/utils.js:698
throw error;
^
TypeError: Cannot read properties of undefined (reading 'db')
at /home/admin/depis/src/lib/db.js:41:49
at /home/admin/depis/node_modules/mongodb/lib/utils.js:695:9
at /home/admin/depis/node_modules/mongodb/lib/mongo_client.js:285:23
at connectCallback (/home/admin/depis/node_modules/mongodb/lib/operations/connect.js:367:5)
at /home/admin/depis/node_modules/mongodb/lib/operations/connect.js:554:14
at Object.connectHandler [as callback] (/home/admin/depis/node_modules/mongodb/lib/core/sdam/topology.js:286:11)
at Timeout._onTimeout (/home/admin/depis/node_modules/mongodb/lib/core/sdam/topology.js:443:25)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
The line 41 in db.js is
this.dbClient = connectedClient.db(this.dbName);
But there seems to be no error in the code here, please help.