Estoy usando node/express y cuando quiero hacer la peticion a Mongodb sale este error por consola:
Connected succesfully to mongo
C:\ecommerce\node_modules\mongodb\lib\utils.js:691
throw error;
^
MongoError: MongoClient must be connected before calling MongoClient.prototype.db
at MongoClient.db (C:\ecommerce\node_modules\mongodb\lib\mongo_client.js:347:11)
at C:\ecommerce\lib\mongo.js:27:29
at C:\ecommerce\node_modules\mongodb\lib\utils.js:688:9
at C:\ecommerce\node_modules\mongodb\lib\mongo_client.js:257:23
at C:\ecommerce\node_modules\mongodb\lib\operations\connect.js:283:21
at parseConnectionString (C:\ecommerce\node_modules\mongodb\lib\core\uri_parser.js:611:12)
at connect (C:\ecommerce\node_modules\mongodb\lib\operations\connect.js:281:3)
at C:\ecommerce\node_modules\mongodb\lib\mongo_client.js:256:5
at maybePromise (C:\ecommerce\node_modules\mongodb\lib\utils.js:685:3)
at MongoClient.connect (C:\ecommerce\node_modules\mongodb\lib\mongo_client.js:252:10)
Aca el codigo para conectar a Mongodb. buscando una solucion vi que muchos quitan el número de puerto (${config.port}) de la variable MONGO_URI pero tampoco me ah dado resultado.
archivo mongo.js
// npm i -S mongodb para conecectar a mongodb
const { MongoClient } = require("mongodb");
const { config } = require("../config"); // Obtengo los datos de configuracion de la carpeta "config"
const USER = encodeURIComponent(config.dbUser);
const PASSWORD = encodeURIComponent(config.dbPassword);
const DB_NAME = config.dbName;
//const MONGO_URI = `mongodb://${USER}:${PASSWORD}@${config.dbHost}:${config.dbPort}/?authSource=${DB_NAME}`; // prettier-ignore
const MONGO_URI = `mongodb+srv://${USER}:${PASSWORD}@${config.dbHost}/${DB_NAME}?retryWrites=true&w=majority`;
class MongoLib {
constructor() {
// console.log('MONGO URI: ' + MONGO_URI);
this.client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
this.dbName = DB_NAME;
}
connect() {
return new Promise((resolve, reject) => {
this.client.connect(error => {
if (error) {
reject(error);
}
console.log("Connected succesfully to mongo");
resolve(this.client.db(this.dbName));
});
});
}
getAll(collection, query) {
return this.connect().then(db => {
return db
.collection(collection)
.find(query)
.toArray();
});
}
}
// Exporto la clase para que otros archivos puedan utilizarla
module.exports = MongoLib;