const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
let dataBase;
async function connect() {
const client = await MongoClient.connect('mongodb://localhost:27017');
dataBase = client.db('blog');
};
function getDb() {
if (!dataBase) {
throw { message: "Database connection not established" };
}
return dataBase;
};
module.exports = {
connectToDatabase: connect,
getDb: getDb
};
i keep getting this message
const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms
, this.description);
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305:38) at listOnTimeout (node:internal/timers:559:17) at processTimers (node:internal/timers:502:7) { reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => ServerDescription { _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 }, address: 'localhost:27017', type: 'Unknown', hosts: [], passives: [], arbiters: [], tags: {}, minWireVersion: 0, maxWireVersion: 0, roundTripTime: -1, lastUpdateTime: 85766126, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:382:20) at Socket. (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:302:22) at Object.onceWrapper (node:events:642:26) at Socket.emit (node:events:527:28) at emitErrorNT (node:internal/streams/destroy:164:8) at emitErrorCloseNT (node:internal/streams/destroy:129:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) { [Symbol(errorLabels)]: Set(0) {} } } }, stale: false, compatible: true, code: undefined, [Symbol(errorLabels)]: Set(0) {} }
CodePudding user response:
try to change the 'mongodb://localhost:27017' to 'mongodb://127.0.0.1:27017'
sometimes the localhost is not recognized
I hope it was helpful