使用mongoDB与node.js的驱动程序



我试图使用mongoDB与驱动程序

  1. 我使用这个指南在windows中安装了mongoDB https://medium.com/@LondonAppBrewery/howto -download-install- mongoDB -on-windows-4ee4b3493514。

  2. 我创建了一个新目录和一个app.js。(按照本指南https://docs.mongodb.com/drivers/node/master/fundamentals/connection/)在app.js中,我粘贴了如下内容:

const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://sample-hostname:27017/?maxPoolSize=20&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
  1. 在终端中,我在第一个shell中打开mongod,在第二个shell中使用命令"node app.js">
The terminal printed this error:
C:UsersFederDesktopudemyFruitProjectnode_modulesmongodb-connection-string-urllibindex.js:105
throw new MongoParseError('mongodb+srv URI cannot have port number');
^
MongoParseError: mongodb+srv URI cannot have port number
at new ConnectionString (C:UsersFederDesktopudemyFruitProjectnode_modules←[4mmongodb-connection-string-url←[24mlibindex.js:105:19)
at Object.parseOptions (C:UsersFederDesktopudemyFruitProjectnode_modules←[4mmongodb←[24mlibconnection_string.js:210:17)
at new MongoClient (C:UsersFederDesktopudemyFruitProjectnode_modules←[4mmongodb←[24mlibmongo_client.js:62:46)
at Object.<anonymous> (C:UsersFederDesktopudemyFruitProjectapp.js:8:16)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1072:14)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:937:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:778:12)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)←[39m
←[90m    at internal/main/run_main_module.js:17:47←[39m

不要使用SRV格式的MongoDB URI,因为它需要主机名和有效域名。在您的情况下,您正在连接没有任何域名的localhost。而不是使用

const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb://sample-hostname:27017/?maxPoolSize=20&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
const connection = await client.connect();
if(connection){
console.log("server connected successfully");
}
// Establish and verify connection
// await client.db("admin").command({ ping: 1 });
// console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

有关更多信息,请查看此文档:

https://github.com/mongodb/specifications/blob/master/source/initial-dns-seedlist-discovery/initial-dns-seedlist-discovery.rst seedlist-discovery