![Francisco Garcia [C6]](https://static.platzi.com/media/avatars/avatars/garciafran_c845c2fe-2ea4-42db-a305-a7f4ef13b0fd.jpeg)
Francisco Garcia [C6]
PreguntaBuenas tardes, tengo el siguiente error
TypeError: db.collection is not a function

Luis Lira
El hecho dice que MongoLib no puede invocarse sin
new

David Isaac Flores Medrano
Primero me salio un error: TypeError: Class constructor MongoLib cannot be invoked without 'new'
Le quite el new... y despues me dice
events.js:292 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE: address already in use :::4000 at Server.setupListenHandle [as _listen2] (net.js:1313:16) at listenInCluster (net.js:1361:12) at Server.listen (net.js:1447:7) at Function.listen (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/express/lib/application.js:618:24) at Object.<anonymous> (/Volumes/Data/DEV/GRAPHQL/platzi-dir/index.js:30:5) at Module._compile (internal/modules/cjs/loader.js:1137:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10) at Module.load (internal/modules/cjs/loader.js:985:32) at Function.Module._load (internal/modules/cjs/loader.js:878:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) Emitted 'error' event on Server instance at: at emitErrorNT (net.js:1340:8) at processTicksAndRejections (internal/process/task_queues.js:84:21) { code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen', address: '::', port: 4000 } [nodemon] app crashed - waiting for file changes before starting...

Luis Lira
Es por la forma en que te está conectando a la base de datos, vi tu código y en realidad te está conectando a la base, luego a la colección, luego estás cerrando la conexión del cliente y estás regresando la variable
connection
Con Mongo solo debes usar una conexión en lugar de estar abriéndola y cerrrándola. Aquí te dejo un código de un proyecto donde me conecto a una base de Mongo
const { MongoClient } = require('mongodb') const config = require('../config') const debug = require('debug')('app:mongo') const USER = encodeURIComponent(config.dbUser) const PASSWORD = encodeURIComponent(config.dbPassword) const DB_NAME = config.dbName const MONGO_URI = `mongodb+srv://${USER}:${PASSWORD}@${config.dbHost}/${DB_NAME}?retryWrites=true&w=majority` class MongoLib { constructor() { this.client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) this.dbName = DB_NAME } async connect() { if (!MongoLib.connection) { try { await this.client.connect() debug('Connected successfully to mongo') MongoLib.connection = this.client.db(this.dbName) } catch (error) { debug(error) } } return MongoLib.connection } } module.exports = MongoLib

David Isaac Flores Medrano
Si en la consola me dice que no puede leer la propiedad 'collection' de undefined:
[nodemon] 2.0.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js [nodemon] starting `node graphql index index.js` Server is listening at http://localhost:4000/api TypeError: Cannot read property 'collection' of undefined at getCourses (/Volumes/Data/DEV/GRAPHQL/platzi-dir/lib/resolvers.js:14:28) at processTicksAndRejections (internal/process/task_queues.js:97:5) at async Promise.all (index 0) at async graphqlMiddleware (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/express-graphql/index.js:166:18) (node:4163) UnhandledPromiseRejectionWarning: MongoError: Topology is closed, please connect at processWaitQueue (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/core/sdam/topology.js:1009:42) at NativeTopology.selectServer (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/core/sdam/topology.js:448:5) at executeWithServerSelection (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/operations/execute_operation.js:137:12) at executeOperation (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/operations/execute_operation.js:75:7) at CommandCursor._initializeCursor (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/core/cursor.js:531:7) at CommandCursor._initializeCursor (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/cursor.js:184:11) at nextFunction (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/core/cursor.js:734:10) at CommandCursor._next (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/core/cursor.js:201:5) at fetchDocs (/Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/cursor.js:832:16) at /Volumes/Data/DEV/GRAPHQL/platzi-dir/node_modules/mongodb/lib/cursor.js:855:7 (node:4163) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:4163) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Luis Lira
Hola @blurdesigner no te lanza algún error en tu consola? la base de datos que estás consultando sí tiene información agregada? Porque podría pasar que esté teniendo un error que se atrapa en el catch y te devuelve el array vacío que inicializaste o simplemente la colección que está consultando no tiene información.

David Isaac Flores Medrano
Hola @Luis_LiraC a mi en GraphiQL me devuelve un array vacío:
{ "data": { "getCourses": [] } }
Qué podrá estar mal???
Aquí está mi código: https://github.com/iblurdesigner/graphql/tree/hotfix

Luis Lira
Genial, mucho éxito :D 💚 ¡Nunca pares de aprender!
![Francisco Garcia [C6]](https://static.platzi.com/media/avatars/avatars/garciafran_c845c2fe-2ea4-42db-a305-a7f4ef13b0fd.jpeg)
Francisco Garcia [C6]
Luis muchas gracias, ya supere el problema con su ayuda. Si era un problema de versión
"dependencies": { "dotenv": "^8.2.0", "express": "^4.17.1", "express-graphql": "^0.11.0", "graphql": "^15.3.0", "graphql-tools": "^6.0.12", "mongodb": "^3.5.9" },

Luis Lira
Podrías desinstalar mongo con npm uninstall mongo mongodb, borrar la carpeta de node_modules, el package-lock.json y luego instalar todo de nuevo, junto con la versión más reciente de mongodb con npm i mongodb@latest. Actualmente mongodb está en la versión 3.5.9 y ahí tienes la 2.2.33.
![Francisco Garcia [C6]](https://static.platzi.com/media/avatars/avatars/garciafran_c845c2fe-2ea4-42db-a305-a7f4ef13b0fd.jpeg)
Francisco Garcia [C6]
Creo que si puede ser la versión de Mongo, le copio lo que tengo en package.json
dependencies": { "dotenv": "^8.2.0", "express": "^4.17.1", "express-graphql": "^0.11.0", "graphql": "^15.3.0", "graphql-tools": "^6.0.12", "mongo": "^0.1.0", "mongodb": "^2.2.33" }, "devDependencies": { "nodemon": "^2.0.4", "standard": "^14.3.4" },
Cuando ejecuto con los cambios me sale este error.
the options [useNewUrlParser] is not supported the options [useUnifiedTopology] is not supported
y en el explorador
{ "message": "Failed to fetch", "stack": "TypeError: Failed to fetch" }