Can anyone give me an example of a mongodb connection URL in c9.io? I'm wanting to connect to their local instance of mongodb and I have mongod running in the background.
Here is what I'm trying to use:
var mongodb = require('mongodb');
function ConnectToDB(mongoUrl){
var MongoClient = mongodb.MongoClient;
//var url = 'mongodb://localhost:27017/my_database_name';
var url = mongoUrl || 'mongodb://' + process.env.IP + ":27017/test";
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if(err){
console.log(err);
}
console.log("Connected correctly to server");
return db;
});
}
It doesn't even log, any help would be much appreciated.
I got this to work my logic was off a bit :p
function OpenDB(mongoUrl, callBack){
var MongoClient = mongodb.MongoClient;
//var url = 'mongodb://localhost:27017/my_database_name';
var url = mongoUrl || "mongodb://" + process.env.IP + "/test";
console.log(url.bgWhite.blue);
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if(err){
console.log(err);
}
console.log("Connected correctly to server");
callBack(db);
db.close();
});
}
Related
I am Getting Error While Connecting My Node.js Application to Mlabs Database. I am Using the Below Code, Please Tell me Where I am Wrong.
var express = require('express');
var app = express();
const MongoClient = require('mongodb').MongoClient;
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11';
app.get('/', function(req, res) {
MongoClient.connect(MONGO_URL, { useNewUrlParser: true }, (err, db) => {
if (err) {
return console.log('Error While Connecting to mongodb');
}
db.collection("users").find({_id:"5b50e2d3e712fa3g8a8e9a76"}, function(err,result){
if(err){
console.log('Error While Finding data from your table');
}else{
console.log(result);
}
})
});
});
app.listen(process.env.PORT || 5000);
Thanks In Advance.
Using the same connection string in your code, I console.log the error and got "MongoNetworkError: failed to connect to server". To fix this, make sure the connection string
const MONGO_URL = 'mongodb://dbUser:dbpassword#ds132251.mlab.com:33623/testing11'
is correct
and also make sure that your network is fine and can connect to mlab.
I'm unable to export the db object for using in my routers (controller). Heres the file where i connect to the database and attempt to export db object:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
database = db;
module.exports = database;
});
and where i try using it in one of my routers:
var db = require('../path/to/file/above');
// Redirect to application
router.get('/', function(req, res, next) {
try {
db.close();
} catch (err) {
console.log(err);
}
res.render('index',{});
});
"console.log(err)" says "db.close() is not a function".
Q: How do i properly export the db object so i can use it in my routers?
i think there is some problem with your module.exports try this
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(db);
});
}
module.exports = connectMongo;
You can use mongoskin to access the mongodb and can export the db object.
e.g.
var mongo = require('mongoskin');
var url = 'mongodb://localhost:27017/database';
var db = mongo.db(url, {native_parser:true});
module.exports = db;
And, in your router,
var db = require('../path/to/file/above');
// Redirect to application
router.get('/', function(req, res, next) {
try {
//some db operations
} catch (err) {
console.log(err);
}
res.render('index',{});
});
Other solution is to pass the callback as suggested by #Asif.
This is what my database file (database.js) ended up to be:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var express = require('express');
var app = express();
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
database = db;
});
// Returns DB object when called
module.exports.get = function() {
return database;
}
and using it like this (note that you have to call the get function in a router.get() for example, calling it directly won't work since the connection won't be open yet):
var database = require('./database.js');
var assert = require('assert');
var express = require('express');
var router = express.Router();
// Redirect to application
router.get('/', function(req, res, next) {
var db = database.get();
// Mongo Query here
res.render('index',{});
});
I'm new in node.js and mongo db and i have done my code like this in all my routes.
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var ObjectID = mongo.ObjectID;
var collection;
//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
//connection error or success message
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
throw err;
} else {
console.log("connected to the mongoDB");
}
//index
router.get('/', function(req, res) {
collection = db.collection('category');
collection.find({}).toArray(function(err, category) {
collection = db.collection('subcategory');
collection.find({}).toArray(function(err, subcategory) {
collection = db.collection('product');
collection.find({}).toArray(function(err, product) {
collection = db.collection('banner');
collection.find({status: 'A'}).toArray(function(err, banner) {
console.log(banner);
res.render('home',
{
title : 'Home',
categorys : category,
subcategorys : subcategory,
products : product,
banner : banner
}
);
});
});
});
});
});
});
module.exports = router;
please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance
Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.
NodeJS Mongo Driver default connection pool size is 5.
Important: db and categoryCollection variables are kept outside each requests.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
categoryCollection = db.collection('category');
app.listen(3000);
console.log('Listening on port 3000');
});
app.get('/', function(req, res) {
categoryCollection.find({}).toArray(function(err, category) {
});
});
You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
if (err) throw err;
});
and in your routes you can now access MongoDB without having to write any connection code.
I try MongoDB connect to My chat application with node.js. I have google and read lot's of article but I cant figure it out.
it's throw's arror like:
{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }
Following my code :
var app = require('express')();
var http = require('http').Server(app);
var https = require('http')
var io = require('socket.io')(http);
var sockets = new Array;
var clients = new Array;
var webSockets = {}; // userID: webSocket
var userlist = {};
var allClients = [];
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/products';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
//Close connection
db.close();
}
});
I had this problem and it turned out I had to replace localhost with 127.0.0.1 and it worked
I have a nodejs app which connects to Mongodb installed locally with the code :
var mongo = require('mongodb');
var nodemailer = require("nodemailer");
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('clients', server, {safe:false});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'clients' database");
db.collection('clients', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'clients' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findAll = function(req, res) {
db.collection('clients', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Now I want to move this code to Heroku. According to Heroku, my code should look something like :
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('mydocs', function(er, collection) {
collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
});
});
});
I can't seem to figure out how to restructure my code for it to work on Heroku.
Does it have to be on heroku?
You could keep your code on Heroku, easily configure a free Mongodb instance/datasource in Mongolab ( https://mongolab.com/products/pricing/ ) and adjust your code to connect to the free Mongodb instance on Mongolab:
mongodb://dbuser:dbpassword#dfs12345.mongolab.com:56789/dbname
Ref: http://docs.mongolab.com/connecting/