我无法使用节点驱动程序建立与 mongodb 的连接。 这是我的代码:
**const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
// connection URL
const url = "mongodb://localhost:27017/";
// database Name
const dbName = "fruitsDB";
// 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 to server successfully");
const db = client.db(dbName);
client.close();
});**
这是我得到的回复:
我已经尝试将 url 中的地址从“localhost”更改为“127.0.0.1”,但没有成功。 请帮帮我!
我相信您需要添加
directConnection=true
标志来强制您的操作在连接 URI 中指定的主机上运行。
const client = new MongoClient(url, {
useNewUrlParser: true,
directConnection: true,
});
参考: https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#direct-connection