开发者问题收集

在 javascript 中连接到 mongoose 数据库时出错

2020-07-24
169

我正在运行此代码:

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!'));

我得到了这个输出:

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)

有人能解释一下发生了什么吗?

2个回答

您必须传递一个回调函数:

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

请参阅相关帖子: TypeError [ERR_INVALID_ARG_TYPE]

tpschmidt
2020-07-24

我建议像这样与 mongoose 连接。

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