We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Define Schema
import * as mongoose from 'mongoose'; export type Schema = mongoose.Schema; export class SchemaFactory { static createSchema(options: any): Schema { return new mongoose.Schema({ ...options, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, }); } }
Create Provider to inject Model ( created from Schema )
const CompanySchema = SchemaFactory.createSchema({ name: { type: String, required: true, maxLength: 75 }, }); const companyProvider = { provide: `EXAMPLE_MODEL`, useFactory: (connection: Connection) => connection.model('Company', CompanySchema ), inject: ['DatabaseConnection'], }; export const databaseProviders = [ { provide: 'DatabaseConnection', useFactory: (): Promise<typeof mongoose> => mongoose.connect(MONGODB_URL, mongooseOptions), }, ]; @Module({ imports: [], providers: [...databaseProviders, companyProvider], exports: [...databaseProviders, companyProvider], })
Usage
@Module({ imports: [DatabaseModule], controllers: [HealthController], }) export class HealthModule {} @Controller('health') export class HealthController { constructor( @Inject('COMPANY_MODEL') private companyModel: Model<Company>, ) {} @Get() async check() { await this.companyModel.create({ name: 'dasd' }); const totalOfCompany = await this.companyModel.count(); console.log({ totalOfCompany }); return {totalOfCompany} }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
2nd Create Schema and Model in NestJS with Mongoose
The text was updated successfully, but these errors were encountered: