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',{});
});
Related
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);
});
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'm trying to use MongoDB with Node/Express. I made the official example work:
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
insertDocuments(db, function() {
db.close()
})
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
// Some code
], function(err, result) {
// Some code
callback(result)
})
}
app.get('/insert-document', function(req, res) {
// res.send()
})
How can I make it so that Mongo is available inside Express' HTTP methods? For instance, to use insertDocuments() inside app.get('/insert-document', function(req, res)?
EDIT (full server.js file):
var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')
var app = express()
var compiler = webpack(config)
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null)
assert.equal(3, result.result.n)
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result)
})
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
}
}))
// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))
app.get('/docs', function(req, res) {
// res.send()
insertDocuments(db, function() {
db.close()
})
})
app.listen(8080, 'localhost', function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:8080')
})
I get
TypeError: Cannot read property 'collection' of undefined
at insertDocuments (/home/alex/node/project-mongo/build/dev-server.js:24:22)
Refer codes here, save the connection db as one global variable, sample codes as below.
var db;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/insert-document', function(req, res) {
// insertDocuments() could invoked here.
});
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();
});
}
var express = require('express');
var routes = require('./routes');
var socket = require('socket.io');
var fs = require('fs');
var app = module.exports = express.createServer();
var Server = require('mongodb').Server,
Db = require('mongodb').Db,
Connection = require('mongodb').Connection;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});
db.open(function(err, db) {
console.log('opened');
app.listen(3000);
});
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
var array = collection.findOne({word:'TEST'}, function(err, item) {});
console.log(array);// <----always "undefined"
});
});
I try to insert the object into the database. And by using "console.log(array)" everytime,I find that it always be "undefined". Is it can't be insert into the database or can't be found from the database. How can I solve it??
But, The 'console.log(item)' shows 'null'. So does it sucessfully insert into the database, or should I change another way to get the object from database.
collection.findOne is asynchronous, so you don't use the return value of the function; instead, you should console.log(item) from inside your (currently empty) callback.
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
collection.findOne({word:'TEST'}, function(err, item) {
console.log(item);
});
});
});