mb64-connect
v2.0.8
Published
This repository contains code for connecting to a MongoDB database using the `mb64-connect` package.
Readme
mb64-connect
mb64-connect is a MongoDB and Mongoose wrapper designed for Node.js applications. It simplifies database connections and schema validation, allowing you to define reusable schemas accessible throughout your project.
Features
- Easy MongoDB Connection: Quickly connect to MongoDB with one function.
- Reusable Schema Validation: Define schemas once and reuse them across your project for CRUD operations.
- Efficient & Lightweight: Reduces redundant code and keeps your project organized.
Installation
Install via npm:
npm install mb64-connectUsage Examples
Step 1: Connecting to MongoDB
Use connectDB to connect to MongoDB with your connection string.
//index.js
const express = require('express');
const app = express();
const main = require("./src/main.js")
const connectDB = require("mb64-connect");
app.use(express.json());
connectDB(process.env.MONGO_URI);
app.use("/api",main)
app.listen(PORT, () => {
console.log(`Auth server running on http://localhost:${PORT}`);
});
//main.js
const express = require("express");
const router = express.Router();
const Signup = require("./AuthFunctions/Signup.js");
const Login = require("./AuthFunctions/Login.js");
router.post("/signup", Signup);
router.post("/login", Login);
module.exports = router;Step 2: Setup Schema Using connectDB.validation
Define a schema for the User collection using connectDB.validation. This schema can be reused anywhere in your project by simply referencing the collection name.
const connectDB = require("mb64-connect");
const userSchema = {
name: { type: String, required: true, minLength: 3, maxLength: 50 },
email: { type: String, required: true, unique: true, match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
password: { type: String, required: true, minLength: 8 },
};
const User = connectDB.validation("User", userSchema, true); Step 3: Implementation of connectDB.validation
This example demonstrates using the User schema to validate incoming data, check for existing users, and create a new user if validation passes.
//Signup.js
const connectDB = require("mb64-connect");
const userSchema = {
name: { type: String, required: true, minLength: 3, maxLength: 50 },
email: { type: String, required: true, unique: true, match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
password: { type: String, required: true, minLength: 8 },
};
const User = connectDB.validation("User", userSchema, true);
async function Signup(req, res) {
// Access the "User" collection validation
const { error } = User.validate(req.body);
if (error) return res.status(400).send({ error: error.details[0].message });
try {
const existingUser = await User.findOne({ email: req.body.email });
if (existingUser) {
return res.send({ message: "User with this email already exists", canLogin: true });
}
const savedUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
res.status(201).send({
message: "User created successfully",
userId: savedUser._id,
});
} catch (err) {
console.error("Error creating user:", err);
res.status(500).send({ error: "Internal Server Error" });
}
}Example 4: Reuse connectDB.validation
Use the existing User schema to validate login credentials, ensuring you don’t need to redefine the schema or model.
//Login.js
const connectDB = require("mb64-connect");
const User = connectDB.validation("User");
async function Login(req, res) {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || user.password !== password) {
return res.send({ error: "Invalid email or password", login: false });
}
res.status(200).send({
message: "Login successful",
login: true,
});
} catch (error) {
console.error("Error logging in:", error);
res.status(500).send({ error: "Internal Server Error", login: false });
}
}API Reference
connectDB(connectionString)
Establishes a connection to MongoDB.
- connectionString: MongoDB URI string.
connectDB.validation(collectionName, schema, [timestamps])
Creates a reusable schema validation for a MongoDB collection, accessible by the collection name.
- collectionName: Name of the MongoDB collection.
- schema: Object defining fields, data types, and validations.
- timestamps: Optional. Boolean to enable timestamps (
createdAtandupdatedAtfields).
License
This project is licensed under the MIT License.
