我做了一个简单的程序来连接到我的 mongoDB 数据库
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const bodyParser = require('body-parser');
let db = null;
const url = 'mongodb://localhost:27017';
const dbName = 'chatbotdb';
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({extended: false});
app.use(jsonParser);
app.use(urlencodedParser);
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("This log is never shown.");
db = client.db(dbName);
});
app.listen(3000);
console.log('Server running on: localhost:3000'); //this log is always shown
我希望看到连接到 mongoDB 的日志,我已经安装了 MongoDBCompass 并且我的服务器正在运行
node.js 驱动程序延迟连接,因此在执行某些需要连接到服务器的操作之前,您实际上不会看到任何到服务器的连接。
db = client.db(dbName)
无需连接即可使用客户端可用的数据执行。
尝试 ping,因为这需要服务器的响应。