Sharing a MongoDB connection with other js files - javascript

Using Node.js/Express.js/Monk.js, I'm trying to share my MongoDB connection with other JS files.
In apps.js, I had declared:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
require('./libs/mylib');
(db works fine)
In /lib/mylib.js I had:
var db = require('db');
But I get the error: Error: Cannot find module 'db'
How can I make this db connection available through all my js libs ? (and is it the right approach?)

In apps.js
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
In /lib/mylib.js
var db = require('../apps.js')
Though i would reccommend making a separate file called db.js and in that file export the connection ,that is more cleaner.

Related

How to reuse Redis connection using nodeJs childProcess

How could I reuse the redis connection in processes created using Childprocess.fork() in nodeJs ?
For example, I would have a redis-config.js file where I create an instance of RedisClient and connect to the redis server.
So after that I would have another file, test.js for example, and inside that file test, js I would access the instance of redis via import and then I could for example insert a key in redis. But this without creating another connection to the redis server.
For example
redis-conf.js
const Redis = require('redis');
const redisClient = Redis.createClient({name:'test-conecction'});
module.exports = {redisClient:Object.freeze(redisClient)}
main.js
const cp = require('node:child_process');
const {redisClient} = require('./redis');
redisClient.connect().then(()=>{ <<=== this is want i want, this does not work, i want to connect only once.
const c1 = cp.fork('./child.js');
const c2 = cp.fork('./child.js');
})
child.js
const {redisClient} = require('./redis');
redisClient.info().then((data)=>{ <<== when i try this, nodeJs tells that the client is disconnected
console.log(data);
})
IN resume. Its not possible. Because when nodeJs create a childPorcess evething is re-created and all resources are re-alocated.

Export mysql2 connection to other files node js

I am trying to use one connection across all the files in a node and mysql2 project.
This is what I did ->
// db.js
const mysql = require('mysql2')
const connection = mysql.createConnection({dbinfo})
console.log(connection) // the connection is proper
module.exports = { connection }
//server.js
const { con } = require('./db')
console.log(con) //returns undefined
Similar thing works if I use the mysql package instead with mysql2

Node.js require connection inside multiple module

I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.
An example of connection file: db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
and one of the various files to manage the routes:
const app = express();
const router = express.Router();
const db = require('./db');
router.get('/save',function(req,res){
// some code for db
});
module.exports = router;
Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?
How many times will my connection be created?
There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:
require("./db") === require("./db") // true

Where are required modules visible?

I have a problem understanding NodeJS require().
Basically I have this 3 files:
moongooseconfig.js
var config = require('./config');
var mongoose = require('mongoose');
module.exports = function() {
var db = mongoose.connect(config.db);
require('../app/models/user.server.model');
return db;
}
usercontroller.js
var User = require('mongoose').model('User');
exports.create = function(req, res, next) {
var user = new User(req.body);
user.save(function(err) {
if(err) {
return next(err);
} else {
res.json(user);
}
});
};
And the server.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongooseconfig');
var express = require('./config/express');
var db = mongoose();
var app = express();
app.listen(3000);
My understanding of require was that the required module is only visible in the JS file which required the module.
I do not get why the user controller can use the mongoose Model 'User' without requiring the model file.
Yet the mongooseconfig requires the model file inside a function without saving it to a variable.
Can somebody tell me what happens there? Can every file access modules once they where required anywhere?
(Maybe I 'm just to blind, but I can not find the answer in the Node docs and googling "nodejs require scope" does not gave me any good results)
Comments to answer:
mongoose keeps a reference to each of its models. require is just regular JavaScript; it returns an object, and that object has no unusual restrictions on it. The require in mongooseconfig.js is still necessary, though; without it, app/models/user.server.model[.js] will never run and register a model with mongoose.

MongoDB Mongoose state persistence

When you do this in a main.js module:
var db = require('mongoose');
db.connect('mongodb://localhost/piautomation');
var myOwnModule = require('./myOwnModule');
And myOwnModule.js:
var db = require('mongoose');
Is db using a persisted mongoose connection or do you have to wrap the mongoose module in your own module to persist the connection?
Below is the wrapped version.
main.js code:
var dbConnect = require('./dbConnect'),
myOwnModule = require('./myOwnModule');
dbConnect.js code:
var db = require('mongoose');
module.exports = db.connect('mongodb://localhost/piautomation');
myOwnModule.js code:
var persistedDb = require('./dbConnect');
No, you don't need to do that.
On application start up, you can do the following:
var db = require('mongoose');
db.connect('mongodb://localhost/piautomation');
Connections are pooled internally by mongoose
From the Mongoose Docs
Each connection, whether created with mongoose.connect or mongoose.createConnection are all backed by an internal configurable connection pool defaulting to a size of 5.

Categories

Resources