node.js - MongoDb 与 Node js 的连接

标签 node.js mongodb

我需要使用我的 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/

相关文章:

javascript - 如何强制特定包的转译

python - PyMongo 统计

spring - MongoDB比较运算符与null

mongodb - 如何在 Linux 中禁用对 MongoDB 3.0.x 的匿名访问

node.js - Express Passport.js 未在 session 中保留用户对象

javascript - 如何在使用 Passport.js 成功登录后刷新用户的用户名?

MongoDB docker 容器不显示数据库

node.js - mongodb mongoose js更新不插入新字段

javascript - NodeJS - 设置 mean.io 找不到模块错误

javascript - Passport - 动态覆盖策略