I connect mongodb with monk
in app.js
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
app.use(function(req,res,next){
req.db = db;
next();
});
It working fine here . But now I add index.js in routes folder
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
exports.index = function(req, res){
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', { "userlist" : docs});
});
res.render('index', { title: 'Express' })
};
It also working fine. But I am connecting DB both in app.js and index.js . Which thing I need to do that connection define in app.js is accessible in index.js
The two solution I know are:
Put the connection in another file, import that file.
db.js
var monk = require('monk');
module.exports = monk('localhost:27017/nodetest1');
Other files:
var db = require('./db.js');
Or pass the same connection around:
app.js:
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var module = require('./myModule.js')(db);
myModule.js:
module.exports = (db) => {
//...
};
Or:
app.js:
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var module = require('./myModule.js');
module.init(db);
myModule.js:
var db;
exports.init = (masterDb) => {
db = masterDb;
};
And ensuring db
is set before using it.
create a separate file like database.js
and put the code in it:
module.exports = {
url : 'mongodb://localhost/productecom'
};
and require this file where you need database connection:
like in index.js:
var database = require('./database');
mongoose.connect(database.url);
my example has mongodb and different url, make the change as per your need since I dont know about monk
maybe you need to export whole monk configuration., it will work
Just create a simple db.js file with database connection and require your connection whenever you need to use it as follows:
db.js
var monk = require('monk');
module.exports = monk('localhost:27017/nodetest1');
app.js
...
var db = require('./db.js');
app.use(function(req,res,next){
req.db = db;
next();
});
index.js
var db = require('./../db.js');
exports.index = function(req, res){
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', { "userlist" : docs});
});
res.render('index', { title: 'Express' })
};
Credits to @DrakaSAN who share same concept.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.