使用node js连接到mongoDB服务器

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

我无法使用节点驱动程序建立与 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();
});**

这是我得到的回复: Response image of terminal

我已经尝试将 url 中的地址从“localhost”更改为“127.0.0.1”,但没有成功。 请帮帮我!

node.js mongodb node-mongodb-native
1个回答
0
投票

我相信您需要添加

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

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