MongoDB 无法正常运行 - 如何排除故障

问题描述 投票:0回答:1

我已经通过zip文件在我的Windows 11中安装了MongoDB,我还在我的环境变量路径中添加了MongoDB文件的bin文件夹的路径。但是当我尝试运行我的代码时,代码执行但无法运行任何内容。

我在下面添加我的代码。我还添加了 cmd 的图像;因为你可以清楚地看到它已经执行了代码,然后什么也没做。

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

const connectionURL = 'mongodb://127.0.0.1:27017';
const databaseName = 'task-manager';

MongoClient.connect(connectionURL, (error,client)=> {
    if(error){
        return console.log('Unable to connect to database',error);
    }
    console.log('Connected Successfully');
})

enter image description here

在上面的代码中,我们可以看到这是非常基本的代码,在上面的代码中我只是尝试打印“已成功连接”以确保数据库已成功连接。

不幸的是它没有被打印出来。

javascript node.js mongodb mongoose node-modules
1个回答
0
投票

首先,

MongoClient
是一个需要使用
new
关键字实例化的类。此外,
MongoClient.connect
函数是一个异步函数,它返回一个 Promise,您可以在其中使用
then/catch
async/await
。使用
then
catch
,您的代码应如下所示:

const mongodb = require("mongodb");

const connectionURL = 'mongodb://127.0.0.1:27017';
const dbclient = new mongodb.MongoClient(connectionURL /*insert connection options here*/);

dbclient.connect()
    .then(() => {
        console.log("Connected Successfully");
        // Execute logic here after connect
    })
    .catch((err) => {
        console.log("Unable to connect to database", err);
    });

请注意,连接后您想要发生的任何事情都需要进入

then
回调函数。我建议将此代码放入
async
函数中,然后使用
await
连接函数,因为代码看起来会更干净。

© www.soinside.com 2019 - 2024. All rights reserved.