MongoDB Mongoose state persistence - javascript

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.

Related

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

Node.js mongoose connect error

I have node.js project which contain mongo database. I use mongoose schema. 3 file in project are: index.js, users.js and db.js. when I want to connect mongodb via mongoose, I can't. Here is my code. when it runs it says
"error is: TypeError: parseFn is not a function."
pls help!!
db.js
const mongoose=require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/myDB', { useNewUrlParser:true}).then(
(res) => {
console.log("Success!!.")
}).catch((e) => {console.log("error is: " + e);});
users.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema= new Schema({
id:{type : Number, required: true, unique:true},
username : String,
password : String }, {collection: 'userTB'});
var userS= mongoose.model('userTBL', userSchema);
module.exports=userS;
index.js
...
var db=require('./app_server/models/db');
...
I'm not sure but I guess I faced the same kinda error when I was a newbie in MongoDB. If I'm not wrong this error is because you haven't actually started your local MongoDB server yet. You actually have to start the MongoDB server manually to connect to it. The command to start mongo server from the terminal is something like:
mongod --dbpath /data/db

Mocha running slow. Takes as long as 8s to perform the complete test suite

I am using Mocha with mongoose. The tests are running very slow and take a long time to execute, sometimes as long as 8s. I am connected to a local mongo database on my system.
The relevant files are as follows:
test_helper.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
//before executed only once for the entire test suite
before((done)=>{
mongoose.connect('mongodb://localhost:20000/users_test');
mongoose.connection
.once('open',()=> {done();})
.on('error',(error)=>{
console.warn('Warning',error);
});
});
//define a hook - a function that gets executed before any test runs
beforeEach((done)=>{
mongoose.connection.collections.users.drop(()=>{
//ready to run the next test!
done();
});
});
user.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name:String,
postCount:Number
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
the tests are spread across several files. I have uploaded the files on drive and the links are:
update_test.js - https://drive.google.com/open?id=1fHO8gLrRE3QsRfRfbwbpOOEg0zcGGxPL
reading_test.js - https://drive.google.com/open?id=1Kck1GS8j07MCQyYf0a1xpiGJ3lvvowLF
delete_test.js - https://drive.google.com/open?id=1KLt61139ey4BXg0HC9p8V3_Q5fH0UP39
create_test.js - https://drive.google.com/open?id=1AN2d2gq70UnNky5_4GQ6_fKlxj28WEA-

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.

Sharing a MongoDB connection with other js files

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.

Categories

Resources