status 503 when heroku node app try to access to mlab db add-on with monk - mongodb

I'm trying to deploy my express-mongodb app on heroku. I've already tryed to access locally to the heroky mlab addon and with the local server works fine. But when I start the same server on heroku it looks like the server can't solve the requests because of the db lack. I'm wondering if the problem is with monk js or something else.
<!-- language: lang-javascript-->
const express = require('express');
const bodyParser = require('body-parser');
const monk = require('monk');
const engines = require('consolidate');
const app = express();
const router = require('./routes/router');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(`${__dirname}/public`));
app.set('views', `${__dirname}/templates`);
app.engine('html', engines.mustache);
app.set('view engine', 'html');
const db = monk('mongodb://<xxxx>.mlab.com:15338/heroku_1xx37v0b');
db.then(() =>{
console.log("connection success");
}).catch((e)=>{
console.error("Error !",e);
});
app.use((req, res, next) => { req.db = db; next(); });
app.use('/', router);
app.listen(process.env.PORT || 3000);
// ask something to the db
const collection = db.get('docUtenti');
collection.findOne({type: "docTotUtenti" }).then((doc) => {console.log(doc);})

Related

Connecting my express app on cpanel to my mongodb database

I have a simple express application that I have connected to the online mongo database (i.e on mongodb.com),
the app works fine on localhost but once I hosted the app on cpanel the app is no longer able to post data to the online mongo database even after allowing the database to be accessible by all IP addresses, what could be the issue?
Here is the code on my server file
const mongoose = require('mongoose');
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const UserRoutes = require('./routes/users')
mongoose.connect('mongodb+srv://admin:shulemate#shulematecluster.qlyycac.mongodb.net/school?retryWrites=true&w=majority',{useNewUrlParser:true,useUnifiedTopology:true});
const db = mongoose.connection
db.on('error',(err)=>{
res.json({err});
});
db.once('open',(req,res)=>{
res.json({message:'A db connection was established!'});
});
const app = express();
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json());
app.use(morgan('dev'))
app.set('view engine','ejs');
const PORT = process.env.PORT || 3000
app.listen(PORT,()=>{
console.log(`App running on port ${PORT}`);
});
app.get('/',(req,res)=>{
res.render('home')
})
app.use('/api/user',UserRoutes);
I have tried allowing access to my database by all IP addresses but it still isn't working

Heroku app successfully deployed but error when loading site

I am new to heroku so please try to help me by explaining step by step
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command
heroku logs --tail
this is my server.js file
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const connectDB = require('./config/db')
const passport = require('passport')
const bodyParser = require('body-parser')
const routes = require('./routes/index')
connectDB()
const app = express()
if( process.env.NODE_ENV === 'development' ){
app.use(morgan('dev'))
}
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(routes)
app.use(passport.initialize())
require('./config/passport')(passport)
const PORT = process.env.PORT || 3000
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on ${PORT}`))
this Procfile
web:node server.js

Cannot connect to MongoDB - Authentication Failed

Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!

mongoDB, mongoose, cannot connect to DB

First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors
keys.jss
module.exports = {
mongoURI: 'mongodb+srv://john:<********>#mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};
I might be following an outdated tutorial so certain things might be 'unnecessary'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
// Connect to Mongo
mongoose
.connect(db, {useNewUrlParser: true} )
.then(() => console.log('monogoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started on port ${port}'));
Rather than displaying port '5000' i would get an error (different each time)
message: '3rd parameter to mongoose.connect() or mongoose.createConnection() must be a function, got "object"',
name: 'MongooseError'
Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.
I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect(db, dbOptions, function(error) {
// we had an error of some kind
if (error) {
console.error(error);
// better yet, we don't want to app to run without our DB!
throw error;
}
// If we made it here, no errors came up
console.log('monogoDB Connected...');
// Start up the app!
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
});
Here is how it would look with the promise structure:
const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );
const app = express();
// Bodyparser Middleware
app.use( bodyParser.json() );
// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect( db, dbOptions )
.then( () => {
console.log( "monogoDB Connected..." );
// Start the application
const port = process.env.PORT || 5000;
app.listen( port, () => {
console.log( `Server started on port ${port}` );
} );
} )
.catch( err => {
console.log( err );
throw err;
} );

Mongo DB connects successful but does not create database

const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Connect to mongoose
mongoose.connect('mongodb://localhost:27017/sample')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.get('/', (req, res) => {
const title = 'Welcome';
res.send('ok');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I have written this code to connect MongoDB and there is no issue with the connection but when I show my DBS using "> show dbs", I can't see the sample database which I have created. My system is windows 32 bit.
Just connecting to the database won't create it. You need to add something to the database like saving a new document or adding an index.