Miki
Miki

Reputation: 113

Listen is not a function

I have this code and it say this error

TypeError: app.listen is not a function

 at mongoose.connect (C:\wamp\www\curso-mean2\index.js:14:7)
 at C:\wamp\www\curso-mean2\node_modules\mongoose\lib\connection.js:292:19
 at open (C:\wamp\www\curso-mean2\node_modules\mongoose\lib\connection.js:576:17)

[nodemon] app crashed - waiting for file changes before starting...

Contents of app.js:

'use strict'

var express = require('express'); // objeto express dentro de variable app
var bodyParser = require('body-parser');

var app = express();

// cargar rutas
//configurar body parser
//es necesario para body parse y convierte a objetos Json los datos que llegan por http:
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//configurar cabeceras http

//rutas base

//exportamos el modulo , podemos utilizar express dentro de ficheros que incluyan app
module.exports = app;

Contents of index.js:

'use strict'

var mongoose = require('mongoose');
var app = require('./app');
//configurar puerto por defecto
var port = process.env.PORT || 3977;

mongoose.connect('mongodb://localhost:27017/curso_mean2', (err,res) => {
    if (err){
        throw err;
    }else{
        console.log("La base de datos esta funcionando muy bien...");
        //a escuchar
        app.listen(port, function () {
            console.log("Servidor del api rest de musica escuchando en http://localhost");
        });
    } //else
});

Can you help me, please? I'm a beginner, and I don't know what is happening

Upvotes: 0

Views: 2219

Answers (1)

J DAVID MARES S
J DAVID MARES S

Reputation: 31

the underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser, so you should use something similar like this:

mongoose.connect('mongodb://localhost:27017/curso_mean2', { useNewUrlParser: true, useUnifiedTopology: true })

If you wanna catch errors, I suggest you use promises and catch method:

mongoose.connect('mongodb://localhost:27017/curso_mean2', { useNewUrlParser: true, useUnifiedTopology: true })
 .then(()=>{
       console.log("La base de datos esta funcionando muy bien...");

       app.listen(port,function () {
           console.log("Servidor del api rest de musica escuchando en http://localhost");
       });

 })
 .catch( err => console.log(err) );

Here you can found references from connection to MongoDB

Upvotes: 2

Related Questions