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-express-multi-db

v0.0.2

Published

mongoose express middleware to allow multiple connections depending on the origin

Downloads

9

Readme

mongoose-express-multi-db

:warning: Even if I'm actively working on it, the library is still in beta. Use it at your own risk

motivation

For multitenant projects you might have the need to have multiple connections to a mongoDB instance where each tenant has its own database. Sadly mongoose does not allow this, as it does not allow reusing a connection for different databases. With the native mongoDB client it's not an issue at all. Using mongoose makes it insanely hard to do!

Installation

This is a Node.js module available through the npm registry.

Installation is done by running

$ npm install mongoose-express-multi-db

Usage

JS

simple

The following example will get the db name from the origin and apply it to search for the db. (in this case it will be the db localhost)

    const mongooseMiddleware = require("mongoose-express-multi-db")

    ...

    app.use(mongooseMiddleware({
        mongoUri: "mongodb://localhost:27017/",
        modelsPaths: "absolute/path/to/models"
    }))

    app.get("/user", (req, res)=>{
        const myCoolId = ...
        const user = req.tenant.getModel("users").findOne({_id: myCoolId}).lean()
        res.json(user)
    })

db depends on something else

This example shows how the db can be chosen by different factors like a jwt token if you have always the same origin :). Here you can also verify that no other db is being accessed (you should always watch out nobody touches the admin db!)

    const mongooseMiddleware = require("mongoose-express-multi-db")
    const jwt = require('jsonwebtoken')
        
    ...

    app.use(mongooseMiddleware({
        mongoUri: "mongodb://localhost:27017/",
        modelsPaths: "absolute/path/to/models",
        getDBName: (req)=>{
            const token = req.headers.authorization.split(' ')[1]
            if(token){
                const decoded = jwt.verify(token, "mySecret")
                return decoded.targetDB
            }else{
                return "authdb"
            }
        }
    }))

express ends before the server closes (avoid memory leaks)

If you are testing the functions the connections should be closed before opening them again. This is a common issue with jest or mocha. So just write something like this

    const mongooseMiddleware, {killMiddlewareConnections} = require("mongoose-express-multi-db")

    ...

    app.use(mongooseMiddleware({
        mongoUri: "mongodb://localhost:27017/",
        modelsPaths: "absolute/path/to/models"
    }))

    server = app.listen(PORT, () => console.log(`server started: Port:${PORT}`));
    server.addListener("close", () => killMiddlewareConnections(app))

TS

Add model typings

In order to get typings you need to define what models do what. You might put the type KnownModels in a separate file. You have to update it each time you need it in order not to have type errors


import mongooseMiddleware, {Tenant} from "mongoose-express-multi-db"
...

// You can use the type or the type of the model, it has the same result
import type MyCollectionModel from "absolute/path/to/models/MyModel"
import { MyType } from "absolute/path/to/models/MyModel"

type KnownModels = {
    FromModel: typeof MyCollectionModel, // Model<MyCollection> (Model<{name:string}>)
    FromType: MyType // MyType ({name:string})
}

declare global {
    namespace Express {
        interface Request {
            tenant: Tenant<KnownModels>
        }
    }
}
app.use(mongooseMiddleware<KnownModels>({
    mongoUri: uri,
    modelsPaths: "absolute/path/to/models"
}))

// Works the same with models and types
const MyElement1 = req.tenant.getModel("FromModel").findOne().lean() // {name:string} | null
const MyElement2 = req.tenant.getModel("FromInterface").findOne().lean() // {name:string} | null