我需要使用我的 Nodejs 应用程序设置 Mongo DB。我在 mongoDb Atlas 中创建了一个帐户,并尝试使用我的用户名和密码将我的应用程序与以下 URL 连接。不幸的是,我收到身份验证失败错误。
const MongoClient = require("mongodb").MongoClient;
const CONNECTION_URL = "mongodb+srv://<username>:<password>@renj0-2herp.mongodb.net/test?retryWrites=true";
const DATABASE_NAME = "example";
var app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
var database, collection;
app.post("/person", (request, response) => {
collection.insert(request.body, (error, result) => {
if(error) {
return response.status(500).send(error);
}
response.send(result.result);
});
});
app.get("/people", (request, response) => {
collection.find({}).toArray((error, result) => {
if(error) {
return response.status(500).send(error);
}
response.send(result);
});
});
app.listen(3001, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("people");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
});
最佳答案
const CONNECTION_URL = 'mongodb://username:password@localhost:27017/example'
您的连接网址错误,所以我建议您尝试此格式或也尝试以下
const CONNECTION_URL = 'mongodb://localhost:27017/example'
关于node.js - MongoDb 与 Node js 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55117898/