npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-multi

v2.0.1

Published

Create multiple Mongoose connections to severals DBs; supports also gridfs

Downloads

244

Readme

mongoose-multi

Create multiple Mongoose connections to severals DBs.

Note: gridfs support was removed in 1.0.0

Installation

npm install mongoose-multi --save

Getting started

Use the module in your code

The syntax is 'database.collection' for maximum clarity.

db.application.customer.find().exec(function(err, docs) {
  // do sth. here with customers
});

"customer" is the mongoose model and can use it's methods. See http://mongoosejs.com/docs/guide.html.

Start the Module

Idea:

  • network configuration in separate file (different modes for production, development, etc.)
  • schemas in separate file
// Start the module in the application
var   dbConfig = require('./config.js').db,  // external network file
      mongooseMulti = require('mongoose-multi'),
      db = mongooseMulti.start(dbConfig, node.env.PWD + './schemas.js'); // schema file path => mongoose-multi trys to require it


// wait for connection to be open
db.application.mongooseConnection.once('open', function () {

    // use it
    db.application.customer.find().exec(function(err, docs) {
      // do sth. here with customers
    });

    db.books.article.findOneAndUpdate().exec(function(err, doc) {
      // do sth. here with article
    });

    db.application.customer.findExactOne({}, function(err, doc) {
       // err if no or more than one docs are found
       // do sth. here with customer
    });

    db.books.article.findMinOne({}, function(err, doc) {
      // err if no docs are found
      // do sth. here with article
    });

 });

Network config file

You might integrate this your way in your config. mongoose-multi needs one object with all database urls to connect to.

 module.exports = {
     "db":{
         "application": 'mongodb://localhost:27017/application',
         "book": 'mongodb://localhost:27017/books'
     }
 };

Mongoose Schemas file

 // mongose is needed here for the definition
 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;


 module.exports = {
     application:{ // database

         customer: new Schema({ // collection
             mailaddress: {type: String},
         }),

         settings: new Schema({ // collection
             customerId: {type: String, required: false},
             options: {type: Array, required: false},
         }),

     },

     book:{ // database

         article: new Schema({ // collection
             description: {type: String},
             numOfPages: {type:Number, required: false},
             weight:{type:Number, required: false},
         }),

         paperback: new Schema({ // collection
             description: {type: String, required: false},
             numOfPages: {type:Number, required: false},
             weight:{type:Number, required: false},
         })
     }

 };

Advanced Schema file options

Option 1: If you need to modifie the schemas in your code, you can do so and then directly pass the object for all schemas.

// Start the module
 var  dbConfig = require('./config.js'),  // external network file
      schemaFile = require('./schemas.js'),  // external schema file
      mongooseMulti = require('mongoose-multi'),
      db = mongooseMulti.start(dbConfig, schemaFile);   

// use "db" in your app  ..

Option 2: For bigger projects you can have a schema file folder. Each database has one file with it's name.

// Start the module
 var  dbConfig = require('./config.js').db,  // external network file
      mongooseMulti = require('mongoose-multi'),
      db = mongooseMulti.start(dbConfig, node.env.PWD + './schemas'); // try to require all schema files within folder

// use "db" in your app  ..

./schemas/application looks like:

 /** schemas for db application
 * @version 0.0.2
 */
 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;

 module.exports = {
    customer: new Schema({ // collection
        mailaddress: {type: String},
   }),

   settings: new Schema({ // collection
        customerId: {type: String, required: false},
        options: {type: Array, required: false},
   }),

 };

./schemas/book looks like:

/** schemas for db book
* @version 0.0.4
*/
 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;

 module.exports = {

         article: new Schema({ // collection
             description: {type: String},
             numOfPages: {type:Number, required: false},
             weight:{type:Number, required: false},
         }),

         paperback: new Schema({ // collection
             description: {type: String, required: false},
             numOfPages: {type:Number, required: false},
             weight:{type:Number, required: false},
         })

 };

Network config file

The network file may include all urls to your databases:

 module.exports = {
     "db":{
         "application": 'mongodb://localhost:27017/application',
         "book": 'mongodb://localhost:27017/books'
     }
 };

Alternative you can also pass options:

 module.exports = {
    module.exports = {
        db: {
            online: {
                url: "mongodb://localhost:27017/auditoria",
                options : {useNewUrlParser: true}
            },
            history: {
                url: "mongodb://otheHost:27017/db_arquitectura",
                options : {}
            }
        }
    }
 };

Reuse the mongoose connection

The original mongoose connection is also returned for every DB to use it in other own modules, or especially the events like:

   // we assume a database "application"

   db.application.mongooseConnection.once('open', function() {
      console('db application now open');
      startSomething(db); // start after db is ready
   });

Mongoose reconnection issues

There have been several issues, that prevent a correct reconnect to the databse. In many cases, one might never see a disconntect, but a app in production should reconnect reliable. In this version we simple terminate the process after 10 seconds disconnect and restart it automatic with pm2. This might be changed in the future, when there is a better and reliable workaround. Check if this is for your process.

Development

Install the dev tools with

npm install

Then you can runs some test cases and eslint with:

npm test

ToDo

  • tests