mongodb-web-beast
v1.0.0
Published
MongoDB Web Beast - Modern MongoDB ORM for Node.js with chainable API, validation, and relationships.
Downloads
1
Maintainers
Readme
MongoDB Web Beast
A modern MongoDB ORM for Node.js with chainable API, validation, and relationships. Built on top of Mongoose for robust MongoDB operations.
Built with ❤️ by Web Beast - Your Ultimate Web Development Resource
Features
✅ Modern API - Familiar methods like User.paginate(10), User.create({...})
✅ Chainable Queries - where(), orWhere(), whereHas(), orderBy(), select()
✅ Developer Experience - Type-safe with TypeScript, intuitive API, works with JavaScript and TypeScript
✅ Built with Mongoose - Robust MongoDB ODM
✅ Validation - Simple, expressive validation rules
✅ Relationships - Easy relationship handling with with() and whereHas()
✅ Pagination - Built-in pagination with metadata
Installation
npm install mongodb-web-beast mongooseQuick Start
import mongoose from 'mongoose'
import { Model } from 'mongodb-web-beast'
// Define your schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
status: { type: String, enum: ['active', 'inactive'], default: 'active' }
})
// Create your model
export class User extends Model {}
User.init(userSchema)
// Use modern methods
const users = await User.paginate(10)
const newUser = await User.create({ name: 'John', email: '[email protected]' })
const activeUsers = await User.where('status', 'active').get()Basic Usage
Creating Records
// Create a single record
const user = await User.create({
name: 'Brij Patel',
email: '[email protected]',
status: 'active'
})
// Create multiple records
const users = await User.createMany([
{ name: 'John', email: '[email protected]' },
{ name: 'Jane', email: '[email protected]' }
])Finding Records
// Find by ID
const user = await User.find('507f1f77bcf86cd799439011')
// Find by ID or throw error
const user = await User.findOrFail('507f1f77bcf86cd799439011')
// Get first record
const firstUser = await User.first()
// Get first record or throw error
const firstUser = await User.firstOrFail()
// Get all records
const allUsers = await User.all()Query Builder
// Basic where clause
const activeUsers = await User.where('status', 'active').get()
// Multiple conditions
const users = await User
.where('status', 'active')
.where('age')
.gte(25)
.lte(40)
.get()
// OR conditions
const users = await User
.where('status', 'active')
.orWhere('status', 'pending')
.get()
// IN conditions
const users = await User.whereIn('status', ['active', 'pending']).get()
// LIKE search
const users = await User.whereLike('email', '@gmail.com').get()
// NULL checks
const users = await User.whereNull('deletedAt').get()
const users = await User.whereNotNull('email').get()Ordering and Selecting
// Order by field
const users = await User.orderBy('name', 'asc').get()
const users = await User.orderBy('createdAt', 'desc').get()
// Select specific fields
const users = await User.select('name email').get()
const users = await User.select(['name', 'email', 'status']).get()Pagination
// Basic pagination
const result = await User.paginate(10, 1)
console.log(result.data) // Array of users
console.log(result.pagination)
// {
// current_page: 1,
// per_page: 10,
// total: 100,
// total_pages: 10,
// has_next_page: true,
// has_prev_page: false
// }
// With query conditions
const result = await User
.where('status', 'active')
.orderBy('createdAt', 'desc')
.paginate(20, 2)Relationships
// Include relationships
const posts = await Post.with('author').get()
// Multiple relationships
const posts = await Post.with(['author', 'comments']).get()
// Where has relationship
const users = await User
.whereHas('posts', q => q.where('published', true))
.get()
// Where doesn't have relationship
const users = await User
.whereDoesntHave('posts')
.get()Validation
// Define validation rules
const rules = {
name: { required: true, min: 2, max: 50 },
email: { required: true, email: true },
age: { min: 0, max: 150 },
password: {
required: true,
min: 8,
custom: (value) => {
// Custom validation
if (!/[A-Z]/.test(value)) {
return 'Password must contain at least one uppercase letter'
}
return true
}
}
}
// Validate data
const data = {
name: 'John',
email: '[email protected]',
age: 25,
password: 'weak'
}
const result = await User.validate(data, rules)
if (!result.isValid) {
console.log(result.errors)
}Advanced Queries
// Complex query with multiple conditions
const users = await User
.where('status', 'active')
.where('age')
.gte(25)
.lte(40)
.whereLike('email', '@example.com')
.orderBy('age', 'asc')
.select('name email age')
.limit(10)
.get()
// Count queries
const totalUsers = await User.count()
const activeUsersCount = await User.where('status', 'active').count()
// Exists check
const hasActiveUsers = await User.where('status', 'active').exists()Updates and Deletes
// Update by ID
const updatedUser = await User.update(userId, { status: 'inactive' })
// Update or create
const user = await User.updateOrCreate(
{ email: '[email protected]' },
{ name: 'John Doe', status: 'active' }
)
// Delete by ID
const deleted = await User.delete(userId)
// Delete multiple
const deletedCount = await User.deleteMany({ status: 'inactive' })Model Definition
import { Schema } from 'mongoose'
import { Model } from 'mongodb-web-beast'
const userSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
status: {
type: String,
enum: ['active', 'inactive', 'pending'],
default: 'pending'
},
age: {
type: Number,
min: 0,
max: 150
}
}, {
timestamps: true
})
// Add indexes
userSchema.index({ email: 1 })
userSchema.index({ status: 1 })
export class User extends Model {
// Custom static methods
static async findActiveUsers() {
return this.where('status', 'active').get()
}
static async findUsersByAgeRange(minAge: number, maxAge: number) {
return this.where('age')
.gte(minAge)
.lte(maxAge)
.orderBy('age', 'asc')
.get()
}
// Validation rules
static getValidationRules() {
return {
name: { required: true, min: 2, max: 50 },
email: { required: true, email: true },
status: { required: true },
age: { min: 0, max: 150 }
}
}
}
// Initialize the model
User.init(userSchema, 'users')API Reference
Static Methods
CRUD Operations
create(data)- Create a new recordcreateMany(dataArray)- Create multiple recordsfind(id)- Find record by IDfindOrFail(id)- Find record by ID or throw errorfirst()- Get first recordfirstOrFail()- Get first record or throw errorall()- Get all recordsupdate(id, data)- Update record by IDupdateOrCreate(criteria, data)- Update or create recorddelete(id)- Delete record by IDdeleteMany(criteria)- Delete multiple records
Query Builders
where(field, value)- Add where clauseorWhere(field, value)- Add OR where clausewhereIn(field, values)- Add IN where clausewhereNotIn(field, values)- Add NOT IN where clausewhereNull(field)- Add NULL where clausewhereNotNull(field)- Add NOT NULL where clausewhereLike(field, value)- Add LIKE where clausewhereHas(relation, callback?)- Add relationship where clausewhereDoesntHave(relation, callback?)- Add relationship not exists clausepaginate(perPage, page)- Get paginated resultscount()- Count recordsexists()- Check if records exist
Validation
validate(data, rules)- Validate data against rules
QueryBuilder Methods
Conditions
where(field, value)- Add where clauseorWhere(field, value)- Add OR where clausewhereOperator(field, operator, value)- Add custom operatorwhereIn(field, values)- Add IN where clausewhereNotIn(field, values)- Add NOT IN where clausewhereNull(field)- Add NULL where clausewhereNotNull(field)- Add NOT NULL where clausewhereLike(field, value)- Add LIKE where clausewhereHas(relation, callback?)- Add relationship where clausewhereDoesntHave(relation, callback?)- Add relationship not exists clause
Modifiers
orderBy(field, direction)- Order resultsselect(fields)- Select specific fieldswith(relations)- Include relationshipslimit(limit)- Limit resultsskip(skip)- Skip results
Execution
get()- Get all resultsfirst()- Get first resultfirstOrFail()- Get first result or throw errorpaginate(perPage, page)- Get paginated resultscount()- Count resultsexists()- Check if results exist
Validation Rules
interface ValidationRule {
required?: boolean
email?: boolean
min?: number
max?: number
unique?: boolean
custom?: (value: any) => boolean | string
}Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Inspired by modern Node.js and JavaScript ORM patterns
- Built on top of Mongoose
- Designed for developer experience and productivity
🚀 More from Web Beast
MongoDB Web Beast is proudly created by Web Beast - Your Ultimate Web Development Resource.
🔗 Connect With Us
- 🌐 Website: web-beast.com
- 📧 Contact: Get in touch for custom development solutions
- 💡 Resources: Free templates, tutorials, and development guides
- 📦 GitHub: mongodb-web-beast
🛠️ Our Services
- Web Development: Full-stack solutions with modern technologies
- Node.js Development: Expert Node.js applications and APIs
- React & Vue.js: Frontend development with modern frameworks
- MongoDB Solutions: Database design and optimization
- UI/UX Design: Beautiful and functional user interfaces
