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 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongo-connect-express

v1.0.4

Published

MongoDB connector for Express applications using Mongoose

Downloads

2

Readme

🚀 mongo-connect-express

npm version npm downloads TypeScript License: MIT

A lightweight package for easily connecting Express applications to MongoDB using Mongoose.

✨ Features

  • 🔌 Simple Connection - One-function approach to connect to MongoDB
  • 🔐 Environment Variables - Uses .env for secure connection string storage
  • 📘 TypeScript Support - Full type definitions included
  • 🧩 Minimal Setup - Get connected with just a few lines of code
  • 🗄️ Database Selection - Optionally specify which database to use

📦 Installation

# Using npm
npm install mongo-connect-express

# Using yarn
yarn add mongo-connect-express

# Using pnpm
pnpm add mongo-connect-express

🚦 Quick Start

Step 1: Set up your environment variables

Create a .env file in your project root:

MONGODB_URI=mongodb+srv://username:[email protected]/

Step 2: Connect to MongoDB in your Express app

import express from "express";
import connectMongo from "mongo-connect-express";
import dotenv from "dotenv";

dotenv.config(); // Load .env file

const app = express();
const PORT = process.env.PORT || 3000;

async function startServer() {
  try {
    // ✅ Connect to MongoDB
    await connectMongo();

    // 🚀 Start your Express server
    app.listen(PORT, () => {
      console.log(`🌐 Server running on port ${PORT}`);
    });
  } catch (error) {
    console.error("❌ Failed to start server:", error);
    process.exit(1);
  }
}

startServer();

💡 Usage Examples

Specifying Database Name

await connectMongo({ dbName: "my_database" });

Overriding Connection String

await connectMongo({
  uri: "mongodb://localhost:27017/my_local_db",
  dbName: "custom_db_name", // Optional
});

📚 API Reference

connectMongo(options?)

Connects to MongoDB using Mongoose.

Parameters

| Parameter | Type | Description | Required | | ---------------- | ------ | ------------------------- | ------------------------------------------ | | options | Object | Connection options | No | | options.uri | String | MongoDB connection string | No (defaults to process.env.MONGODB_URI) | | options.dbName | String | Database name to use | No |

Returns

  • Promise<typeof mongoose> - Promise that resolves to a Mongoose instance

⚠️ Error Handling

The function will throw an error if:

  • No MongoDB URI is provided (either in .env or as a parameter)
  • Connection to MongoDB fails
try {
  await connectMongo();
  // Connection successful
} catch (error) {
  console.error("MongoDB connection failed:", error);
  // Handle error appropriately
}

📋 Complete Example

Here's a more complete example including model definition and API routes:

// db/connection.ts
import { connectMongo } from "mongo-connect-express";
import dotenv from "dotenv";

dotenv.config();

export default connectMongo;

// models/User.ts
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

export const User = mongoose.model("User", userSchema);

// server.ts
import express from "express";
import connectMongo from "./db/connection";
import { User } from "./models/User";

const app = express();
app.use(express.json());

// Create a new user
app.post("/users", async (req, res) => {
  try {
    await connectMongo();
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (error) {
    res.status(500).json({ error: "Failed to create user" });
  }
});

// Get all users
app.get("/users", async (req, res) => {
  try {
    await connectMongo();
    const users = await User.find({});
    res.status(200).json(users);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch users" });
  }
});

app.listen(3000, () => console.log("🚀 Server running on port 3000"));

📝 License

MIT © Your Name