@seedcord/plugin-mongoose
v0.4.2
Published
Connect a seedcord bot to MongoDB with Mongoose
Maintainers
Readme
About
@seedcord/plugin-mongoose connects a seedcord bot to MongoDB through Mongoose. It opens the connection during startup, loads every class under dir that carries @RegisterMongooseService, builds each one's model from its schema, and exposes them under the key you attached it on.
It runs on the gateway transport and on http's server runtime. Attaching it to an edge host is a compile error, since Mongoose opens a TCP connection that edge runtimes have no socket for.
Until v1.0.0, minor versions can break.
Installation
pnpm add @seedcord/plugin-mongoose mongoosemongoose, envapt, typescript, and @seedcord/core are peer dependencies.
Attach
attach takes a property name, the plugin class, and its options. Chain it off the constructor:
// bot.ts
import { resolve } from 'node:path';
import { Seedcord } from '@seedcord/gateway';
import { Mongoose } from '@seedcord/plugin-mongoose';
export const seedcord = new Seedcord(config).attach('db', Mongoose, {
dir: resolve(import.meta.dirname, './services'),
uri: Vars.mongoUri,
name: Vars.dbName
});
export default seedcord;// index.ts
import seedcord from './bot';
await seedcord.start();attach returns the instance widened with the key, and seedcord codegen writes db: (typeof Bot)['db'] into seedcord-gen.d.ts off a default import of that module. Calling attach as a bare statement drops the widened type. A named-only export leaves codegen with nothing to import.
Attach before startup. A call after initialization throws CorePluginAfterInit.
Vars stands in for an envapt class. A process.env read types as string | undefined, which the required uri and name reject.
Services
Declare the schema on the class as a public static schema. A class without one is a compile error.
import { MongooseService, RegisterMongooseService } from '@seedcord/plugin-mongoose';
import mongoose from 'mongoose';
interface IUser {
userId: string;
balance: number;
}
@RegisterMongooseService('users')
export class Users extends MongooseService<IUser> {
public static schema = new mongoose.Schema<IUser>({
userId: { type: String, required: true, unique: true },
balance: { type: Number, default: 0 }
});
public async findByUserId(userId: string) {
return this.model.findOne({ userId });
}
}Name each key once so the lookup types resolve:
declare module '@seedcord/plugin-mongoose' {
interface MongooseServices {
users: Users;
}
}Then call it from a handler through core:
const user = await this.core.db.services.users.findByUserId(this.event.user.id);