javascript - Share database connection among multiple routes? -


this question has answer here:

i've created extremely simple node.js app based on express's route-separation example. want power app mongodb driver mongoose. example lists users , kittens.

var express = require('express'); var app = express(); var mongoose = require('mongoose'); var user = require('./user'); var kitten = require('./kitten');  // connect mongodb mongoose.connect('mongodb://localhost/mongoose');  // express config here ...  // user app.all('/users', user.list);  // kitten app.all('/kittens', kitten.list);  // mongoose connection var db = mongoose.connection; db.once('open', function callback () {   var kittyschema = mongoose.schema({ name: string }); });  if (!module.parent) {   app.listen(3000);   console.log('express started on port 3000'); } 

to me seems wise connect mongo database on startup rather each request.

but how share mongoose connection both user , kitten routes? know if didn't need share connection between two, connect database in user.js , kitten.js code.

in node.js when require file, run code in file exactly once. means can store things through closure.

foobardb.js

(function(){   "use strict"; // nice have    var mongoose = require('mongoose'),       databaseconnection;     module.exports = function() {        if ( !databaseconnection ) {            mongoose.connect('mongodb://localhost/mongoose')            databaseconnection = mongoose.connection;       }        (...)   };  })(); 

the databaseconnection shared require("foobardb.js"); do


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -