Can't access MongoDB database with Node library Monk, code works fine on Localhost. Really short, concise code

42 Views Asked by At

So I've been dealing with this problem for some time now, and it has been really resilient considering the little lines of code. I have gone trough the documentation several times and tried many different compositions and options but it just wont work. When on localhost everything works fine, when deployed to the web the app works and I can successfully access the ./ direction which displays "Camisite ", but it gets timeout when trying to access /posts. That's all I know, if someone could provide some advice regarding how to get more information on the error that will be welcome. Just for the testing I have put the connection string directly on the code, otherwise it is on a Now secret.

So here is the code, as I said, it is pretty concise. I cut the post request part for considering it not necessary.

I already tried deleting the || 'localhost/posts' part on the connection string and leave just the string or the string inside a secret.

const express = require('express');
const cors = require('cors');
const monk = require('monk');
const Filter = require('bad-words');
const rateLimit = require('express-rate-limit');

const filter = new Filter();
const app = express();
const db = monk('mongodb+srv://myuserexample:[email protected]/test?retryWrites=true&w=majority' || 'localhost/posts');
const posts = db.get('posts');
app.enable('trust proxy');
app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
    res.json({
        message: 'Camisite! '
    });
});

app.get('/posts', (req, res) => {
    posts
        .find()
        .then(posts => {
            res.json(posts);
        });
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log('server started');
});

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

Okay I solved it, I had the incorrect String since it was for Node Version 3.0 or upper. And I had 2.12 even being a very recent installation. With the correct string it worked fine.

2
CoderFF On

First, you need to add .catch everywhere where you have .then because graceful processing of errors hepls you to cope with situation like this. Print your errors to the console with console.error(), and make log file, at least running your app like this:

node app.js >> stdout.log 2>>stderr.log

This will give you additional information about what happened