reuse moongoose connection in other files - node.js

I realize mongoose is a singleton and once you do mongoose.connect in one file and later all scripts that require this file will have mongoose connected as well.
But shouldn't that mean when I execute another test script that only has require('mongoose') in it and it will show that I am connected to mongodb too because the previous script (which starts an http server) is still running and I am referencing the the same mongoose inside node_modules? Thanks.

UPDATED
Here is an example of a file: myLib.js inside my /lib directory
exports.someVar = [5,4,3,2,1];
exports.printSize = function(){
console.log(exports.someVar.length);
}
Now let's create an other file named app.js and include the myLib.js:
var myLib = require("./lib/myLib.js");
var http = require("./http.js");
console.log("app.js:");
myLib.printSize(); // will print 5
myLib.someVar.push(100);
console.log("app.js:");
myLib.printSize(); // will print 6
console.log("calling http");
http.start();
console.log("app.js:");
myLib.printSize(); // will print 7
Okay, now let's create an other file, named http.js and include the myLib.js too:
var myLib = require("./lib/myLib.js");
exports.start = function(){
console.log("http.js:");
myLib.printSize(); // will print 6
myLib.someVar.push(200);
}
Now lets create a project for myLib.js and replace all lines:
var myLib = require("./lib/myLib.js");
to:
var myLib = require("myLib");
And the result will be the same, that is the why the mongoose connection are active even when you use require("mongoose") in other parts of your project.
After you create a connection, the variable will be available for other parts of your project.
It is like a singleton, so you do not need create your own for hold the connection reference.

Related

In Node, why does 'require' assignment sometimes require curly brackets?

Running some tests through Chai, I noticed the tests would fail under this code:
const add = require('./addition');
//'add is not a function error' even though it's directly exported as a function
But it would pass under this:
const {add} = require('./addition');
Yet when using npm modules, everything is declared without the brackets:
var express = require('express');
var app = express();
var session = require('express-session');
And those are essentially objects with multiple properties to be accessed. Why does it work this way? Is it only function exports that must be assigned as objects explicitly?
This is known as object destructuring. Please refer the link.
For example you have exported a file called sampleFunctions.js which has following functions as exports
function function1(params) {};
function function2(params) {};
module.exports = {
sampleFunc1: function1,
sampleFunc2: function2
}
Now when you need to require it, there are two ways -
when you only need one function(using object destructuring)
let {sampleFunc1} = require('./sampleFunctions');
sampleFunc1();
In this you exposed only the required function not all of the functions exported from that file.
when you want to require all the functions from that file
let sampleFuncs = require('./sampleFunctions');
let samFunc1 = sampleFuncs.sampleFunc1;
samFunc1()

return value to app.js file in node js

I have two files, one called filename and the second called app.js, both files are on the server side. From filename.js filder I am returing a value string from ensureAuthentication method to app.js file, so i export the function:
function ensureAuthentication(){
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
in app.js file i do following
var appjs = require('filename');
console.log(appjs.ensureAuthentication);
result is always is undifined in console??! why is that any idea?
You should try this in your app.js -
var login = require('filename');
console.log(login());
or you can use this :
var login = require('filename')();
console.log(login);
Explanation: Whenever you are exporting a function using exports you need to execute it to get the return value from it.
Try this:
var appjs = require('filename');
console.log(appjs.ensureAuthentication());
note the () after the function call. This will execute your function. The console.log() call will then print the returned value.
Try this, make sure both files are in the same directory. You have a few errors with your code. Missing brackets, and not importing correctly in app.js.
filename.js
function ensureAuthentication(){ // You are missing the brackets here.
return 'tesstestest';
}
exports.ensureAuthentication = ensureAuthentication;
app.js
var appjs = require('./filename'); // You are missing the ./ here.
console.log(appjs.ensureAuthentication()); // Logs 'tesstestest'
Two problems with your code:
You need to require with a relative path (notice the ./):
var appjs = require('./filename');
To get the string value you need to invoke ensureAuthentication as a function:
console.log(appjs.ensureAuthentication());
UPDATE
This update addresses the screenshot posted in the comments.
In the screenshot you pasted in the comments, you have the following line:
module.exports = router
That assigns a different exports object to the module. So your local reference to exports is no longer the same object.
Change that line to
module.exports = exports = router
Which will preserve the reference to exports which you use next.
Here you go with the working code
filename.js
function ensureAuthentication(){
return 'tesstestest';
}
module.exports = {
ensureAuthentication : ensureAuthentication
}
app.js
var appjs = require('./utils/sample');
console.log(appjs.ensureAuthentication());

Express.js db module after refactoring routes

I had a simple app in node/express and after watching a course on the net, it helped me refactor the routes in my app but I found a little problem after doing so.
The problem is that my routes are using a variable called "db" that is an instance of a nedb access point.
var db = {
users: new nedb({ filename: "db/users.db", autoload: true })
};
Of course I can copy the 5 lines of code in the top of every route file to declare it but that would not be very DRY.
I tryed to put it in a separate file and export the variable:
...
module.exports = db;
And then import it in every file with:
var db = require("./db");
...
But this didn't worked as expected (The error was : Cannot find module './db')
This is a simplified structure of my files
db/
users.db
routes/
users.js
app.js
db.js
Any ideas or best practice/elegant way for solving this?
Thank you.
you need to require with a relative path. If you require inside /routes folder, you must write
var db = require("../db");

Dealing with Relative Paths with node.js

I'm wanting to include a .db database file for use with sqlite3 in my node.js project. My problem arises when the module which opens the database connection is required by files in different directories.
My project structure is like so:
project/
|--lib/
| |--foo.js
| `--bar.js
|--db/
| `--database.db
`--server.js
My foo.js file contains opens the database like so:
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('db/database.db');
module.exports = {
foo: function() {
db.serialize(function() { /* Do database things */ });
}
};
This all works fine when foo.js is required from the server.js file like so:
var foo = require('./lib/foo');
But it doesn't work when required from the file inside the lib directory, bar.js.
var foo = require('./foo');
I assume this is because when this file is initiated from the lib directory then the .db file should actually be ../db/database.db.
How can I get around this, what should I do?
the concept current directory differs when using sqlite3.Database function in different scripts. it works as designed in this line of sqlite3 source code.
So you should explicitly specify the current directory every time you use it. According to your project layout, the correct path to database file in lib/foo.js is
var path = require('path')
// specify current directory explicitly
var db = new sqlite3.Database(path.join(__dirname, '..', 'db', 'database.db'));
Then it works no matter where it requires foo.js.

How to export properly in node.js?

I'm running some issues with my node application after upgrading to Express 3.0. So, since I'm rewriting it, I was trying to follow the style of routes/index.js because it looks clean.
So, in my main app.js I have some variables such as:
var calls = 0;
var agents = [];
And also use the node-mysql module. However, the routes definition doesn't have app.js scope but their own scope so calls and agents aren't visible.
How should I make them visible?
For mysql I tried something like:
// libraries/mysql.js
mysql = require('mysql');
var mysql_conf = {
host: myhost,
user: myuser,
password: mypass,
database: mydb
};
var mysql_client = mysql.createClient(mysql_conf);
exports.mysql_client;
//Later in routes/index.js
mysql_client = require('../helpers/mysql.js');
But it seems not to work as it says TypeError: Object #<Object> has no method 'query'
Any hints please?
The line
exports.mysql_client;
Does not actually assign anything to the mysql_client property of exports. It accesses a property, and immediately discards the value. You need to do something like this:
var mysql_client = mysql.createClient(mysql_conf);
exports.mysql_client = mysql_client;
// or simply
exports.mysql_client = mysql.createClient(mysql_conf);

Resources