MongoDB Atlas 连接正常,但在 Heroku 中不显示数据

Sha*_*ngh 4 heroku mongoose

我想在 MongoDB Atlas 中显示我的数据库中的用户。我已成功创建连接,但无法向用户显示。这是我第一次使用 MongoDB Atlas 和 Express。

它在我的系统上运行得很好,但在我的系统上运行 MongoDB,但在 MongoDB Atlas 上运行不正常。

以下是我编写的一些用于连接和显示用户的代码。

mongoose.connect("mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority" ,{useNewUrlParser: true, useCreateIndex: true})
.then(()=>{
    console.log("connected to db");
})
.catch((err)=>{
    console.log("error:",err);
})
Run Code Online (Sandbox Code Playgroud)
let userSchema = new mongoose.Schema({
    name: String,
    email: String,
    credits: Number
})

let User = mongoose.model("user", userSchema);
Run Code Online (Sandbox Code Playgroud)
app.get("/users", function (req, res) {
    // finding the information about all users from the database
    User.find({}, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.render("users.ejs", { result: response });

        }

    })
})
Run Code Online (Sandbox Code Playgroud)

我在 MongoDB Atlas 中指定了 0.0.0.0/0 作为 IP 地址,以便任何人都可以超越它。

我的 MongoDB 图集集合的视图:

我的 MongoDB 图集集合的视图

预期输出:

预期产出

Heroku 给出的输出:

Heroku 给出的输出

我做错了什么?

Est*_*n A 5

我遇到了同样的错误,与 mongoDB Atlas 的连接正常,但我没有从我创建的 dabatase 中获取任何数据。

这个问题是因为连接字符串默认指向一个名为 test 的数据库,正如您在 @cluster0-rpwjk.mongodb.net/ 之后看到的那样。

mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority
Run Code Online (Sandbox Code Playgroud)

所以我解决了更改连接字符串以指向我的数据库名称的问题

mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/MY_DATABASE?retryWrites=true&w=majority
Run Code Online (Sandbox Code Playgroud)