1+ import mongoose from 'mongoose' ;
12import { MyError } from '@boringcodes/utils/error' ;
23
34import { < %= compNamePascalCase % > } from './types' ;
4- import Model , { Document } from './model' ;
5+ import model , { Document , Model } from './model' ;
56
67const list = async ( ) : Promise < < %= compNamePascalCase % > [ ] > => {
78 // list documents
8- const documents = await Model . find ( ) ;
9+ const documents = await getModel ( ) . find ( ) ;
910
1011 return documents . map ( transform ) ;
1112} ;
1213
1314const create = async ( object : Omit < < %= compNamePascalCase % > , 'id' > ) : Promise < < %= compNamePascalCase % >> => {
1415 // create document
15- const document = new Model ( object ) ;
16- await document . save ( ) ;
16+ const document = await getModel ( ) . create ( object ) ;
1717
1818 return transform ( document ) ;
1919} ;
2020
2121const get = async ( id : string ) : Promise < < %= compNamePascalCase % >> => {
2222 // get document
23- const document = await Model . findById ( id ) . exec ( ) ;
23+ const document = await getModel ( ) . findById ( id ) . exec ( ) ;
2424 if ( document === null ) {
2525 throw new MyError ( 'Document not found' ) ;
2626 }
2727
2828 return transform ( document ) ;
2929} ;
3030
31- const update = async ( id : string , object : Omit < < %= compNamePascalCase % > , 'id' > ) : Promise < < %= compNamePascalCase % >> => {
31+ const update = async (
32+ id : string ,
33+ object : Omit < < %= compNamePascalCase % > , 'id' > ,
34+ ) : Promise < < %= compNamePascalCase % >> => {
3235 // get document
33- const document = await Model . findById ( id ) . exec ( ) ;
36+ const document = await getModel ( ) . findById ( id ) . exec ( ) ;
3437 if ( document === null ) {
3538 throw new MyError ( 'Document not found' ) ;
3639 }
@@ -44,7 +47,7 @@ const update = async (id: string, object: Omit<<%= compNamePascalCase %>, 'id'>)
4447
4548const del = async ( id : string ) : Promise < < %= compNamePascalCase % >> => {
4649 // get document
47- const document = await Model . findById ( id ) . exec ( ) ;
50+ const document = await getModel ( ) . findById ( id ) . exec ( ) ;
4851 if ( document === null ) {
4952 throw new MyError ( 'Document not found' ) ;
5053 }
@@ -55,6 +58,11 @@ const del = async (id: string): Promise<<%= compNamePascalCase %>> => {
5558 return transform ( document ) ;
5659} ;
5760
61+ // get model
62+ const getModel = ( ) : Model => {
63+ return mongoose . models [ model . name ] ;
64+ } ;
65+
5866// transform document to <%= compNamePascalCase %>
5967const transform = ( document : Document ) : < %= compNamePascalCase % > => {
6068 const { _id : id , ...restObject } = document . toObject ( {
0 commit comments