gpt4 book ai didi

javascript - 使用promise模块连接mongodb时出错

转载 作者:行者123 更新时间:2023-12-02 22:55:03 25 4
gpt4 key购买 nike

我是 nodejs 的新手。我正在使用 promise 模块进行连接mongodb。但我遇到了以下错误。

(node:6827) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'db' of undefined
at /home/luan1412167/Desktop/nodejs_tutorial/mongodb/promise.js:11:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:6827) 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(). (rejection id: 1)
var Promise = require('promise');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true})
.then(function(err, client){
// if (err) throw err;
if (err) {
console.error('An error occurred connecting to MongoDB: ', err);
}
var db = client.db('Employee');
// db.collection('Employee').updateOne(
// {
// 'EmployeeName' : 'LuanDao'
// },
// {
// $set : {'EmployeeName' : 'AAA'}
// }
// );
client.close();
});

我很努力地修复它。但我还无法修复。任何建议都很感激。非常感谢。

最佳答案

由于您使用了 Promise,因此需要使用 catch 语句修改代码。修改您的代码如下:

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true})
.then((db) => {
var db = client.db('Employee');
}).catch((err) => {
console.error('An error occurred connecting to MongoDB: ', err);
});

关于javascript - 使用promise模块连接mongodb时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58025868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com