mongoose-init
v1.0.3
Published
Instantly generate Mongoose boilerplate for Next.js
Maintainers
Readme
mongoose-init
Instantly generate a Mongoose connection boilerplate in any JavaScript/TypeScript project with a single command.
Usage
npx mongoose-initThis will create a lib/db.ts file in your project with a ready-to-use Mongoose connection.
Generated file
import mongoose from "mongoose";
const MONGODB_URI = process.env.MONGODB_URI || "";
if (!MONGODB_URI) {
throw new Error("Please define MONGODB_URI in your .env file");
}
export async function connectDB() {
try {
if (mongoose.connection.readyState >= 1) return;
await mongoose.connect(MONGODB_URI);
console.log("MongoDB connected successfully");
} catch (error) {
console.error("MongoDB connection failed:", error);
process.exit(1);
}
}Setup
After running the command, add your MongoDB URI to your .env file:
MONGODB_URI=your_mongodb_connection_stringThen import and use it anywhere in your project:
import { connectDB } from "./lib/db";
await connectDB();Works with
- Next.js
- Express
- Plain Node.js
- Any JavaScript/TypeScript project
Author
Sibasish2005
