I've added mLab to my Heroku app, I also use mongoose. I tried use connection string from localhost, and it was working(almost). In my server file I use:
var db = mongoose.connection;
if (process.env.MONGODB_URI) {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect('mongodb://localhost/fitMe')
}
If I open the app from localhost, it saves things to the db, and can get it back, although not everything, but on heroku it doesn't work at all. I use react with server. I think that something wrong with the routs.. so here is the link to server file :
https://github.com/HelenaVolskaia/Motivation/blob/master/server/app.js
You can set an env variable locally and only use this:
// Connect Mongo
mongoose.Promise = global.Promise; // mongoose promises deprecated, use node - mongoosejs.com/docs/promises
mongoose.connect(config.db.MONGODB_URI);
mongoose.connection.once('open', () => { console.log('MongoDB Connected'); });
mongoose.connection.on('error', (err) => { console.log('MongoDB connection error: ', err); });
But regardless, add the on connection error handler and see what the error is, so you can dig deeper into why it's not connecting.
Related
I'm deploying simple express CRUD API with serverless framework. It works fine until it comes to accessing databese, it returns {"message":"Internal Server Error"}. But when running locally it works as intended. Is there a problem with the way I'm connecting to mongoDB?
const mongoose = require("mongoose");
const { logger } = require("../Log/pino");
require("dotenv").config();
mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_URI, {serverSelectionTimeoutMS: 5000});
const connection = mongoose.connection
.once("open", () => {
logger.info("connected to database");
})
.on("error", (err) => {
logger.info(`mongoose error: ${err}`);
});
module.exports = connection;
Fixed it. Problem was that I was only allowing access to mongoDB cluster to requests sent only from my IP. Changed cluster network access settings and it works now as it should.
I am using mongoose to connect to a MongoDB Atlas cluster using the below to start the connection.
However when the connection fails it crashes the whole app and i have to restart it again.
Can anyone tell me the correct way to handle errors with the mongoose connection string in such a way that it leaves the rest of the app running and still listening on my port.
I dont want to worry about re-connecting to mongo in this function if it fails to connect.
console.log("attempting to connect to MongoDB");
mongoose.connect(connectString)
.then((result)=>console.log("Connected to db"))
.catch((err) => {
console.log(err);
return next;
}
)
Use an Error event after your connection
var mongoDB = 'mongodb://localhost:27017/theni';
mongoose.connect(mongoDB, {
useNewUrlParser: true,
useUnifiedTopology: true
});
//Get the default connection
var con = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
con.on('error', console.error.bind(console, 'MongoDB connection error:'));
I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?
I want to connect my app to a database called 'technicaltest'.
My code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
The console ouput:
> set PORT=3001 && node bin/www
Connected to mongoDB !
Same output for this code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console...
But here...
The 'connected' event is call anyway.
I think you forgot to add the port(27017) to your mongodb connection.
It should be
const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});
I have a locally hosted mongodb that I can connect to using mongodb.MongoClient.
Working code:
var mongoClient = require("mongodb").MongoClient;
...
var startApp = function(db) {
// Get our collections in an easy to use format
var database = {
chats: db.collection('chats'),
messages: db.collection('messages')
};
// Configure our routes
require('./app/routes')(app, database);
// START APP
// Start app on port
app.listen(port);
// Tell user the app is running
console.log("App running on port " + port);
// Expose app
exports = module.exports = app;
}
// DATABASE
var database = null;
mongoClient.connect(config.url, function(err, returnDB) {
if(err) {
console.log(err);
} else {
console.log("DB connected");
startApp(returnDB);
}
});
Legacy code that no longer works:
var mongoose = require('mongoose');
...
// Connect to DB
console.log('Connect to database (' + db.url + ')');
mongoose.connect(db.url);
I have added a callback to this connect method but it never gets called (error or no error, this connect function never gets to my callback).
This entire legacy app relies on the API using mongoose to talk to the database so I do not want to redo it all using mongodb. How can I fix this?
*config.url and db.url are loaded from the same file and it is a valid and running mongodb.
It was really easy to fix. Thanks #Bhavik for asking me what version I was using.
I updated mongoose to 4.8.1 by specifying the newest version in packages.json and the issue is resolved.
Tracing the documentation here and failing to load bson apparently. After running npm start I receive:
Snippet:
var mongo = require("mongodb").MongoClient;
//connect to db server
mongo.connect("mongodb://localhost:28017/myDb", function(err, db){
if(!err) {
console.log("Connected to Database")
}
else{
console.log("failed to connect");
}
});
I have tried updating/reinstalling the driver modules as well. Totally new to the framework & db and this type of error feels so trivial that it is discouraging that I am unable to figure it out. Help!
The default port for mongodb is 27017 (and then 28017 is for a web status page).
http://docs.mongodb.org/manual/reference/default-mongodb-port/
Try this connect string:
"mongodb://localhost:27017/myDb"