A
A
Artyom2020-03-27 21:42:48
MongoDB
Artyom, 2020-03-27 21:42:48

Why can't I connect to the database on heroku hosting?

In general, my application uses a remote mongoDB database. Everything works fine on localhost, but after I uploaded my blog to heroku. The database connection fails and no data is loaded. here is the code of the file that uses the database:

const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const urlencodedParser = bodyParser.urlencoded({extended: false});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postScheme = new Schema({
    title: String,
    text: String
});
const Post = mongoose.model("Post", postScheme);

let posts = [];

mongoose.connect("mongodb+srv://admin:<password>@cluster0-emcpv.mongodb.net/blog",
{ useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false });

Post.find({}, (err, docs) => {
    posts = docs;
});

router.get("/", (req, res) => {
    res.render("index", {posts: posts});
});

router.get("/write", (req, res) => {
    res.render("write");
});

router.post("/write", urlencodedParser, (req, res) => {
    const title = req.body.title;
    const text = req.body.text;
    if(title === "" || text === "") {
        res.redirect("/");
    } else {
        const post = new Post({title, text});
        posts.push({title, text});
        post.save();
        res.redirect("/");
    }
});

router.get("/posts/:id", (req, res) => {
    const id = req.params.id - 1;
    res.render("post", {post: posts[id]});
});

module.exports = router;

In the line where the connection goes, the password was removed.
Here is another package.json file:
{
  "name": "blog",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.9.6",
    "pug": "^2.0.4"
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Magnus Keef, 2020-12-21
@SecurityYourFingers

in short,
1) heroku stopped supporting mongodb as a built-in solution:
2) heroku for applications makes dynamic IPs and therefore it is impossible to whitelist the application address in cloud mongo.
as a result, you can test it locally, because you can add your IP to the white list. But bummer, I don't see a free solution yet. If anyone reads, post the recipe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question