我正在尝试连接到 MongoDB,但终端中没有显示任何输出或错误。
这是我的代码
const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
// Connection URL
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "testDB";
// Create a new MongoClient
const client = new MongoClient(url, {useNewUrlParser: true});
// Use connect method to connect to the Server
client.connect(function (err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
Mongod
正在运行,它说正在等待连接,因此它可以正常工作。 testDB 存在,我在里面创建了它mongo
。
这是我的nodeJS 输出 -
$ nodemon
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
就这样,没有别的了。为什么会这样?
尝试使用 async/await 连接数据库
// DB connection
async function connectToDB() {
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
try {
await client.connect();
console.log("Database connected");
} catch (err) {
console.error('Could not connect to the database', err);
} finally {
await client.close(); // Close the connection when done
}
}
connectToDB();
这可能会有所帮助。