MongoDB with Mongoose
Database patterns for user data and credentials storage
Best use case
MongoDB with Mongoose is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Database patterns for user data and credentials storage
Teams using MongoDB with Mongoose should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/mongodb-with-mongoose/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How MongoDB with Mongoose Compares
| Feature / Agent | MongoDB with Mongoose | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Database patterns for user data and credentials storage
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# MongoDB with Mongoose Skill
This skill covers MongoDB database operations for the autoclaim bot.
## Connection Setup
```typescript
// src/database.ts
import mongoose from "mongoose";
export async function connectDatabase() {
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("MONGODB_URI not set");
await mongoose.connect(uri);
console.log("Connected to MongoDB");
}
```
## User Schema Pattern
```typescript
// src/models/user.ts
import { Schema, model, Document } from "mongoose";
interface IHoyolabCredentials {
ltoken: string;
ltuid: string;
cookieToken?: string;
games: string[];
}
interface IEndfieldCredentials {
skOauthCredKey: string;
gameId: string;
server: string;
}
interface IUser extends Document {
discordId: string;
hoyolab?: IHoyolabCredentials;
endfield?: IEndfieldCredentials;
settings: {
notifications: boolean;
autoClaimEnabled: boolean;
};
lastClaim?: Date;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>(
{
discordId: { type: String, required: true, unique: true, index: true },
hoyolab: {
ltoken: { type: String },
ltuid: { type: String },
cookieToken: { type: String },
games: [{ type: String }]
},
endfield: {
skOauthCredKey: { type: String },
gameId: { type: String },
server: { type: String }
},
settings: {
notifications: { type: Boolean, default: true },
autoClaimEnabled: { type: Boolean, default: true }
},
lastClaim: { type: Date }
},
{ timestamps: true }
);
export const User = model<IUser>("User", userSchema);
```
## Common Operations
### Find or Create User
```typescript
async function findOrCreateUser(discordId: string) {
let user = await User.findOne({ discordId });
if (!user) {
user = await User.create({ discordId });
}
return user;
}
```
### Update Credentials
```typescript
async function updateHoyolabCredentials(discordId: string, credentials: IHoyolabCredentials) {
return User.findOneAndUpdate({ discordId }, { $set: { hoyolab: credentials } }, { new: true, upsert: true });
}
```
### Get All Active Users
```typescript
async function getActiveUsers() {
return User.find({
"settings.autoClaimEnabled": true,
$or: [{ "hoyolab.ltoken": { $exists: true } }, { "endfield.skOauthCredKey": { $exists: true } }]
});
}
```
### Delete User Data
```typescript
async function deleteUserData(discordId: string) {
return User.deleteOne({ discordId });
}
```
### Update Last Claim Time
```typescript
async function updateLastClaim(discordId: string) {
return User.findOneAndUpdate({ discordId }, { $set: { lastClaim: new Date() } }, { new: true });
}
```
## Claim History Schema
```typescript
const claimHistorySchema = new Schema({
discordId: { type: String, required: true, index: true },
game: { type: String, required: true },
success: { type: Boolean, required: true },
message: { type: String },
rewards: [
{
name: String,
count: Number,
icon: String
}
],
claimedAt: { type: Date, default: Date.now }
});
// Index for efficient queries
claimHistorySchema.index({ discordId: 1, claimedAt: -1 });
export const ClaimHistory = model("ClaimHistory", claimHistorySchema);
```
## Best Practices
- Always use indexes for frequently queried fields
- Use `lean()` for read-only queries
- Handle connection errors gracefully
- Use transactions for multi-document updates
- Never log or expose raw credentials
## Security Considerations
```typescript
// Encrypt sensitive data before storing
import crypto from "crypto";
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY!;
function encrypt(text: string): string {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-cbc", Buffer.from(ENCRYPTION_KEY, "hex"), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString("hex") + ":" + encrypted.toString("hex");
}
function decrypt(text: string): string {
const parts = text.split(":");
const iv = Buffer.from(parts[0], "hex");
const encrypted = Buffer.from(parts[1], "hex");
const decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.from(ENCRYPTION_KEY, "hex"), iv);
let decrypted = decipher.update(encrypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
```Related Skills
mongodb-expert
MongoDB document modeling, aggregation pipeline optimization, sharding strategies, replica set configuration, connection pool management, and indexing patterns. Use this skill for MongoDB-specific issues, NoSQL performance optimization, and schema design.
mongodb-development
MongoDB development guidelines with Payload CMS, Mongoose, aggregation pipelines, and TypeScript best practices.
mongodb-crud-operations
Master MongoDB CRUD operations, document insertion, querying, updating, and deletion. Learn BSON format, ObjectId, data types, and basic operations. Use when working with documents, collections, and fundamental MongoDB operations.
MongoDB Best Practices
Expert rules for schema design, indexing, and performance in MongoDB (NoSQL).
Developing with MongoDB
The agent implements MongoDB NoSQL database solutions with document modeling, aggregation pipelines, and Mongoose ODM. Use when building document-based applications, designing schemas, writing aggregations, or implementing NoSQL patterns.
mongodb-schema-design
Master MongoDB schema design and data modeling patterns. Learn embedding vs referencing, relationships, normalization, and schema evolution. Use when designing databases, normalizing data, or optimizing queries.
mongodb_usage
This skill should be used when user asks to "query MongoDB", "show database collections", "get collection schema", "list MongoDB databases", "search records in MongoDB", or "check database indexes".
mongodb
MongoDB - NoSQL document database with flexible schema design, aggregation pipelines, indexing strategies, and Spring Data integration
azure-mgmt-mongodbatlas-dotnet
Manage MongoDB Atlas Organizations as Azure ARM resources using Azure.ResourceManager.MongoDBAtlas SDK. Use when creating, updating, listing, or deleting MongoDB Atlas organizations through Azure M...
bgo
Automates the complete Blender build-go workflow, from building and packaging your extension/add-on to removing old versions, installing, enabling, and launching Blender for quick testing and iteration.
nosql-expert
Expert guidance for distributed NoSQL databases (Cassandra, DynamoDB). Focuses on mental models, query-first modeling, single-table design, and avoiding hot partitions in high-scale systems.
nosql-databases
Apply NoSQL best practices for MongoDB, Convex, and document databases. Use when designing schemas, writing queries, optimizing performance, or building applications with non-relational databases. Use with database-expert for query optimization and DBA-level tuning (20+ years experience).