简体   繁体   中英

Error connecting to a mongoose database in javascript

I am running this code:

const mongoose = require('mongoose');
const DB_NAME = 'eventdb';
const HOST = '127.0.0.1:27017';
mongoose.createConnection(`mongodb://${HOST}/${DB_NAME}`,{useNewUrlParser:true});
const db = mongoose.connection;
db.on('error', console.log('Didn\'t connect properly!'));

And I am getting this output:

Didn't connect properly. events:js,111 throw new ERR_INVALID_ARG_TYPE('listener', 'Function'; listener); ^

TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received >undefined at checkListener (events.js:111:11) at _addListener (events.js:348:3) at NativeConnection.addListener (events.js:406:10) at Object. (/Users/sebastianc/Desktop/codeworks/exercises/assessments/weekly->assessment-6/server/Models/event-model.js:11:4)

can anyone shed some light on what is going on?

You have to pass a callback function:

db.on('error', () => console.log('Didn\'t connect properly!'));

See related post on this: TypeError [ERR_INVALID_ARG_TYPE]

I would suggest go with connecting with mongoose like this.

mongoose.connect(`mongodb://${HOST}/${DB_NAME}`,{useNewUrlParser:true}, function (err) {
    if (err) {
        console.log('Mongo Error ' + err);
    } else {
        console.log('MongoDB Connection Established');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM