No data returned on MongoDB using Express router

  • Which version of the application are you using?:
    Bitnami MEAN 3.4.7-0

  • Please choose how you got the application: Installer (Windows, Linux, macOS), cloud image (AWS, GCE, Azure, …) or VM (VMDK, VBOX):
    Ubuntu 14.04.5 LTS (GNU/Linux 3.13.0-126-generic x86_64), AWS

  • Have you installed any plugin or modified any configuration file?:
    No

  • Describe here your question/suggestion/issue (expected and actual results):
    I have a Mongo database set up on a Bitnami Lightsail MEAN stack instance that I am trying to connect to with an Angular/Node/Express application that I am building. I have followed the instructions on how to connect and create SSH Port Forwarding from my local machine (https://docs.bitnami.com/aws/infrastructure/mean/).

I am able access localhost:8888, which gives me access to RockMongo that was set up on the MEAN Lightsail instance with my Mongo database. That being said, I think the configuration for the connection to the server from my local machine is fine.

When I run node server and navigate to the URL (http://localhost:3000/api/numbers) for my api GET method, I am not receiving an error on connecting to the database. Instead, I get the following response, which is basically an empty array of data:

{"status":200,"data":[],"message":null}

Here is the code for my api.js file:

const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;

// Connect
const connection = (closure) => {
    return MongoClient.connect('mongodb://localhost:27017/sakDB', (err, db) => {
        if (err) {
            return console.log(err);
        }

        closure(db);
    });
};

// Error handling
const sendError = (err, res) => {
    response.status = 501;
    response.message = typeof err == 'object' ? err.message : err;
    res.status(501).json(response);
};

// Response handling
let response = {
    status: 200,
    data: [],
    message: null
};

// Get numbers
router.get('/numbers', (req, res) => {
    connection((db) => {
        db.collection('numbers')
            .find()
            .toArray()
            .then((numbers) => {
                response.data = numbers;
                res.json(response);
            })
            .catch((err) => {
                sendError(err, res);
            });
    });
});

module.exports = router;

And the code for my router.js file:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();

const api = require('./server/routes/api');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'dist')));

app.use('/api', api);

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

const port = process.env.PORT || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`Running on localhost:${port}`));

I am beginning to think that this is some configuration issue with MongoDB on the MEAN Lightsail instance. If I try to run db.numbers.find() in MongoDB shell, I get the following error:

MongoDB server version: 3.4.7
> db.numbers.find()
Error: error: {
        "ok" : 0,
        "errmsg" : "not authorized on sakDB to execute command { find: \"numbers\", filter: {} }",
        "code" : 13,
        "codeName" : "Unauthorized"
}

I have to log in as a user mongo sakDB -u admin -p that I created to in order to find data on the collection.

When I try adding those credentials to the connection string mongodb://admin:PASSWORD@localhost:27017/sakDB, I receive a different authentication error:

name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  errmsg: 'Authentication failed.',
  code: 18,
  codeName: 'AuthenticationFailed' }

Hi,

So, let us see if I get this straight. You are unable to obtain the data from your collection unless you are authorized as admin.

I have to log in as a user mongo sakDB -u admin -p that I created to in order to find data on the collection.

However, when you use this connection string it fails:

mongodb://admin:PASSWORD@localhost:27017/sakDB

Maybe it is a problem with the library. Have you checked this getting started guide?

https://docs.bitnami.com/google/infrastructure/mean/get-started/get-started/

Best regards,

Javier J. Salmerón


Was my answer helpful? Click on :heart:

A post was split to a new topic: Not authorized error message when executing command in MongoDB