I am trying to have all my Node modules share one Mongo connection, and am having trouble doing so. I've looked at some of the materials written about this already. Below is the main file, the Mongo helper file, and another file that tries to use the connection. The trouble is that when the route file tries to use the Mongo connection, db is null.
Mongo helper file:
var mongo = require('mongodb').MongoClient
var _db
function connect(callback) {
const host = '---'
const database = '---'
const user = '---'
const pass = '---'
const uri = 'mongodb://' + user + ':' + pass + '#' + host + '/' + database
mongo.connect(uri, (err, client) => {
console.log('Connected to Mongo')
_db = client.db(database)
return callback(err)
})
}
function db() {
return _db;
}
module.exports = {
connect: connect,
db: db
}
Main file:
var express = require('express')
var app = express()
var mongo = require('./helpers/mongo')
mongo.connect((err) => {
if (err !== null) {
console.log("Error connecting to Mongo: " + err)
process.exit()
}
})
var problems = require('./routes/problems.js')
app.use('/problem', problems)
app.listen(3000)
Route file:
var express = require('express')
var router = express.Router()
var db = require('../helpers/mongo').db()
router.get('/stuff', (req, res) => {
var problems = db.collection('problems')
res.send('working correctly')
})
module.exports = router
What about mongoose?
const mongoose = require('mongoose');
// connect to the database (mongodb)
mongoose.connect('mongodb:<host>/<db>', {useMongoClient: true});
mongoose.promise = global.Promise;
var db = mongoose.connection;
// Check for DB connection
db.once('open', function(){
console.log('Connected to Mongo Db');
});
// Check for DB errors
db.on('error', function(err){
console.log(err);
});
Related
i am trying to display all the documents in a collection called tutorial so i am using a simple code here's my code
const mongodb = require("mongodb");
const express = require("express");
var app = express();
var mongoClient = mongodb.MongoClient;
var conn = "mongodb://localhost:27017";
mongoClient.connect(conn, (err, client) => {
if (err) {
console.log(err);
} else {
console.log("connection estableshed");
var db = client.db("mydb");
var collection = db.collection("tutorial");
collection.find().toArray((err, data) => {
console.log(data);
});
client.close();
}
});
but the result i got undefined so what seems to be the problem here?
Problem with the callback, you can use then() method instead.
const mongodb = require("mongodb");
const express = require("express");
var app = express();
var mongoClient = mongodb.MongoClient;
var conn = "mongodb://localhost:27017";
mongoClient.connect(conn).then((err, client) => {
if (err) {
console.log(err);
} else {
console.log("connection established");
var db = client.db("mydb");
var collection = db.collection("tutorial");
collection
.find()
.toArray()
.then((data) => {
console.log(data);
});
client.close();
}
});
app.listen(3000, () => {
console.log("Server started");
});
I am new to nodejs and express.When i try to do get request from the mongoose database in mlab.com i get an empty response.
my serve code is (app.js),
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var db =mongoose.connect('mongodb://test:test#ds155695.mlab.com:55695/app');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected');
});
var user = require('./model/userModel');
var routers = express.Router();
routers.route('/getUSers').get(function(req,res){
user.find(function(err,users){
if(err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use('/api',routers);
app.listen(8000,function() {
console.log('server working');
});
My model is userModel.js
var mongoose = require('mongoose');
var app = mongoose.Schema({
firstName : String,
lastName : String
});
module.exports = mongoose.model('users',app);
can anyone help me where am i going wrong !
What are best practicies to handle mongodb connection using mongoose on production?
This is my code
connectToDatabase.js
'use strict';
const mongoose = require('mongoose');
const mongodb = require('mongodb');
mongoose.Promise = require('bluebird');
const { Db, Server } = mongodb;
const database = 'test';
const connectToDatabase = (callback) => {
if (process.env.NODE_ENV == 'test') return false;
const db = new Db(database new Server('localhost', 27017));
db.open()
.then(() => {
mongoose.connect(`mongodb://localhost/${database}`, { config: { autoIndex: false } });
mongoose.connection
.once('open', () => {
console.log(`Connected to database ${database}`);
callback(db);
})
.on('error', (error) => {
console.warn('Warning', error);
});
});
};
module.exports = connectToDatabase;
app.js
const connectToDatabase = require('./connectToDatabase');
connectToDatabase(() => {
// run server
});
I don't know exactly what happening when connection to database is interrupted, Is mongoose trying connect to database again?
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.