Connect only once to Mongo - node.js

UPDATE: While building an example, I found that the culprit seems to be restify-enroute. The package is messing with mongoose connection. I published the example to https://github.com/HeavyStorm/mongoose-enroute-conflict.
I had understood that mongoose.connect was how to establish a connection between mongoose and Mongo, and supposed that this was a singleton connection of sorts - once called, every module in my app would be able to call Mongo.
This is probably wrong.
My current scenario:
I'm calling connect:
mongoose.connect("mongodb://localhost/test");
My apps structure:
/
/app.js
/modules
./users
./module.js
In app.js I call mongoose.connect. I also load and expose a route from module.js. When I receive a http call, module.js code kicks in (I can see that from the debugger), but as soon as I call mongo (through Model.find() in this case), well, code skips, my callbacks are never called in the client is held on a waiting state.
However, if I add the mongoose.connect line to module.js, the Model.find() yields to the callback almost instantly and the client's receives the response.
TLDR: Do I have to call mongoose.connect on every module that access the database? Why is that?

Related

server crushes after linking mongo atlas,

Server crushed when i linked mongo atlas on the server.js file,error being generated is connection.once is not a functionserver.js file
I have tried to require once as an eventemitter but with no success
I think the way you have implemented this is wrong. When I am looking at another example i.e Mongoose.connection('once') what does it mean it has applied db.once on a DB where as you are doing it on a connection

Closing mongodb connections

I use native mongodb driver with Expressjs, I don't want to open and close connections on a regular basis in my routes. I want to open once use one connection in all my next() functions and then close when done.
I saw that after opening a connection I can pass the db object to next() functions in request object and use it.
When I try to close the connection like var db=req.db; db.close(); it throws an error.
Inorder to solve this issue I have decided to use settimeout function to close my connection.
I can pass around and use the db obj and send response and the after 1-2 seconds db obj is closed by settimeout.
I'm worried if the requests are more will the settimeout functions effect the servers performance. If I use this trick to manage my db connections.
Sorry, I forgot to do:
db=client.db('test')
and:
db.close();
Change in later versions can't directly open db without getting the client, using native mongodb-nodejs driver.

Mongoose request infinite hang

Context:
Mongoose v4.7.6
MongoDB v3.2.11
I'm trying to handle errors related to my database in my software.
I'm stuck in the following problem: When the database is disconnected, mongoose request hang until it get reconnected.
Here is what happend:
I launch my software
It connect to the database though mongoose
I Ctrl+C the mongod process
I get the "Disconnect" and "Close" event from mongoose
I launch a find(...) request
Find request hang
What I've tried so far:
I tried to use in my schema the option bufferCommands who according to the documentation was supposed to make mongoose return an error if there is no available connection, but the result is the same.
What is my code?
mongoose.createConnection(..., {
server: {
// We disable reconnect from mongoose
auto_reconnect: false,
socketOptions: {
// For long running applictions it is often prudent to enable keepAlive.
// Without it, after some period of time you may start to
// see "connection closed" errors for what seems like no reason.
// From mongoose documentation
keepAlive: 1,
},
},
})
The errors are thrown from the mongoose connection directly whenever there is a connection issue, the main server where you make the connection and there are several ways to handle it depending on what you want.
The find query you make is specifically for schema which in the end makes use of main connection object. You'll have to handle it that way for yourself and for users you'll have to configure a timeout for the request being made by them and send them appropriate response.
Cancelling Request based on timeout
This can be done on several levels, your server's logic, your client's end or the mongoose itself.
Follow this person's answer for setting timeout with mongoose, apparently it is not documented properly by mongoose.
https://stackoverflow.com/a/32609226/5225363
For server's logic, you can make a system for specific request that if there is no this then send a response back to client with something else.
On client if no response is received for a specific time then be assured that there is some problem.
p.s By default there is timeout setting for requests

MongoDB connections on require or by function

I am working on a single pager that writes to different mongodb databases through an API setup with express. To do this I have one file named db.js that is doing all of the work with the mongoose module and then exporting the two connections to my express file called app.js.
When I start running my app file with node, my mongo console shows the two connections being made.
My question is, should I be making the exports structured so that they are functions that only connect to the DB when the functions themselves are called? Is there anything bad about leaving the two connections open and waiting for people to use them?
It is better to have your database connections created on start of the application, and leaving them open. The other way to create connections when an API call is made is extremely inefficient, because the connection load increases wrt number of API calls, and also because the response time of the API increases.
In db.js export your objects.
In your app.js, you can directly require the appropriate connection and start using it
var db = require("../db").first;
db.find({}, function (err, res) {})

How to properly structure database calls in an express/mongoose application?

What is the correct way to access a mongodb database from Express ?
Right now, I am including my database handler db.js which contains mongoose.connect( 'mongodb://localhost/db' ); every time I need to do a database call.
Should I use the same connection and passing my db object through callbacks or I can just include my db file every time ?
In other words, is mongoose.connect always re-using the same connection ?
Edit: my source code is public here, I am fairly new to nodejs/express applications and I am not sure if my application is structured properly...
You only need to connect to your database once. In your other files, you need to include your models and use them to read / write to your database collections.
Edit: Looking at your code -- why don't you move your connect into your initialization script, and then include db.js to access your models?

Resources