【问题标题】:Setting "useNewUrlParser" & "useUnifiedTopology" to true in mongodb connection url, avoids the catch block in a promise function在 mongodb 连接 url 中将“useNewUrlParser”和“useUnifiedTopology”设置为 true,避免了 promise 函数中的 catch 块
【发布时间】:2021-01-09 13:38:17
【问题描述】:

在我的代码中,我使用了 mongoose 来建立一个 mongodb url 连接。为避免出现“DeprecationWarning”,我将“useNewUrlParser”、“useUnifiedTopology”、“useFindAndModify”、“useCreateIndex”设置为 true。

但是,这避免了 catch 块错误。 例如:如果我在我的 atlas url 中输入了错误的凭据,则此代码不会在控制台中显示错误。

const url = require('./setup/myUrl').mongoUrl

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose
    .connect(url)
    .then(() => console.log('DB is connected...'))
    .catch(err => console.log(`Error: ${err}`));  

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    @Mehedi Hasan catch 块仅处理初始连接错误,要处理从 DB 发生的错误,您需要注册 db.on('error', () => {}); 事件。

    例如:

    mongoose.connect(dbPath, {
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
    }).catch((err) => {
        console.error(err.message); //Handles initial connection errors
        process.exit(1); // Exit process with failure
    });
    
    const db = mongoose.connection;
    db.on('error', () => {
        console.log('> error occurred from the database');
    });
    db.once('open', () => {
        console.log('> successfully opened the database');
    });
    module.exports = mongoose;
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 2021-12-18
      • 2018-10-31
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2020-07-30
      • 2011-09-03
      相关资源
      最近更新 更多