I am using yeoman's angular-fullstack
generator as reference
I want to know how does MongoDB maintain connection as the connection to the DB is done in the main app.js
file and after that there is no reference sent to next files/modules(that use the DB) for the same connection. Other files/modules just require
the mongoose
and start working on it as if the mongoose
is passing the reference for the connection.
Please clarify these question:
I have been using Node.js with cassandra,elasticsearch,redis and neo4j for some time but never came to notice this type of working practice for any of the above. Is this best practice ?
some code reference:
app.js
:
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
thing.model.js
:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ThingSchema = new Schema({
name: String,
info: String,
active: Boolean
});
module.exports = mongoose.model('Thing', ThingSchema);
mongoose is a singleton, I've noticed a few other node modules do this too, like winston. That means any time you require mongoose, you're loading a reference to the same instance everywhere, connections and all. I realized this particularly when I accidentally had two simultaneous mongoose libraries, and models added to one instance could not be loaded from the other. Because I have several node modules talking to the database, I ended up exporting my models from one shared package instead of doing require('mongoose') all over the place.
Agreed with @mattcasey . That should sum up questions 1 and 2.
As for 3, you're going to have to clarify that. Mongoose doesn't currently support any database other than MongoDB so I'm not sure what you're asking.
Most helpful comment
mongoose is a singleton, I've noticed a few other node modules do this too, like winston. That means any time you require mongoose, you're loading a reference to the same instance everywhere, connections and all. I realized this particularly when I accidentally had two simultaneous mongoose libraries, and models added to one instance could not be loaded from the other. Because I have several node modules talking to the database, I ended up exporting my models from one shared package instead of doing require('mongoose') all over the place.