MongoDB Guide
Use MongoDB with Mongoose for flexible, schema-based data modeling in your Express.js application.
Initialize with MongoDB
xacos init my-api --ts --mongodbConnection Setup
Configure your MongoDB connection in .env:
MONGODB_URI=mongodb://localhost:27017/mydbDefine Models
Create Mongoose schemas in src/models:
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
name: string;
password: string;
createdAt: Date;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
name: { type: String, required: true },
password: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
export default mongoose.model<IUser>('User', UserSchema);CRUD Operations
import User from '../models/user.model';
// Create
const user = await User.create({
email: 'user@example.com',
name: 'John Doe',
password: 'hashed_password'
});
// Read
const users = await User.find({ active: true });
const user = await User.findById(id);
// Update
await User.findByIdAndUpdate(id, { name: 'New Name' });
// Delete
await User.findByIdAndDelete(id);Indexes and Performance
UserSchema.index({ email: 1 });
UserSchema.index({ createdAt: -1 });
UserSchema.index({ name: 'text' });