appolo mongo module
npm install @appolo/mongoMongo module for appolo built with appolo-mongo and mongoose
``typescript`
npm i @appolo/mongo
| ModelRepository injection id | string| modelRepository|
| connection | mongo connection string | string | null |
| config | mongose connection options | object | {} |
| exitOnDisconnect | call process.exit on disconnect | boolean | false |$3
| key | Default
| --- | --- |
| keepAlive | true |
| useNewUrlParser | true |
| useCreateIndex | true |
| autoReconnect | true |
| reconnectTries | Number.MAX_VALUE |
| reconnectInterval | 500 |
in config/modules/all.ts`typescript
import {MongoModule} from '@appolo/mongo';export = async function (app: App) {
await app.module(new MongoModule({connection:"mongo://mongo-connection-string"}));
}
`Usage
`typescript
import {define, singleton} from 'appolo'
import {schema,prop,Model,model,Ref,injectModel,Doc} from "@appolo/mongo";@model()
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
@prop(Address)
address:Address
}
@schema()
export class Address{
@prop({type:String})
street:string
@prop({type:String})
city:string
}
@model()
@schema()
export class Comment{
@prop({type:String})
text:string
@prop({ref:User})
user:Ref
}
@define()
@singleton()
export class SomeManager {
@injectModel(User) userModel:Model;
async getUser(id:string): Promise> {
let user = await this.userModel.findById(id)
return user;
}
}
`
Schema
$3
#### @schema(collectionName:string,options:SchemaOptions)
define new schema with collectionName and mongose schema options
`typescript
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
@prop(Address)
address:Address
}
`
$3
The prop decorator define class property to the Mongoose schema as a property
`typescript
@prop({ type:String })
firstName: string;
``$3
define sumDocument`typescript
@schema()
export class Address{
@prop({type:String})
street:string
@prop({type:String})
city:string
}
@schema()
export class User{
@prop(Address)
address:Address
}
`$3
add ref to another mongoose schema
the ref schema must be defined as model with model
`typescript
@model()
@schema()
export class User{
@prop()
name:string
}@model()
@schema()
export class Comment{
@prop({ref:User})
user:Ref
}
`$3
define any field as array using []
`typescript
@prop([ type: String ])
names?: string[];@prop([Address])
addresses:Address[]
@prop([{ref:User}])
user:Ref[]
`$3
define required field
`typescript
@prop({ type:String ,required:true})
firstName: string;
``$3
define index field
`typescript
@prop({ index: true })
name?: string;
`$3
define unique field
`typescript
@prop({ unique: true })
someId?: string;
`
$3
define enum field
`typescript
enum Gender {
MALE = 'male',
FEMALE = 'female',
}
@prop({ enum: Gender })
gender?: Gender;`$3
define field with default
`typescript@prop({ type: String,default:"myName" })
name?: string;
`
$3
validate using minlength / maxlength / match / min /max same as mongoose
`typescript
@prop({ minlength: 5, maxlength: 10, match: /[0-9a-f]*/ })
phone: string;
``$3
or use custom validator same as mongoose
`typescript
@prop({
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
}
},
message: props => ${props.value} is not a valid phone number!
})
phone: string;
``$3
define virtual getter setters as in mongoose
`typescript
@prop()
firstName?: string;@prop()
lastName?: string;
@virtual() // this will create a virtual property called 'fullName'
get fullName() {
return
${this.firstName} ${this.lastName};
}
set fullName(full:string) {
const [firstName, lastName] = full.split(' ');
this.firstName = firstName;
this.lastName = lastName;
}`
$3
define static method as in mongoose
the method will be created on the mongose model
`typescript
@staticMethod()
static findByName(this: Model, name: string) {
return this.findOne({ name });
}
``typescript
@define()
@singleton()
export class SomeManager { @injectModel(User) userModel:Model & typeof User;
async getUser(name:string): Promise> {
let user = await this.userModel.findByName(name)
return user;
}
}
`
you need added the typeof User in order to use the static method findByName$3
define instance method as in mongoose
instance methods are created on mongoose document`typescript
@method()
addAge(this: Doc,age?:number) {
this.age = this.age + (age ||1 );
return this.save();
}
`$3
define mongoose pre hooks
the pre function will be executed before the defined hook
`typescript
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
@pre("save")
private preSave(this:Doc,next){
if (this.name === 'aaa') {
this.name = 'bbb';
}
next();
}
}
`$3
define mongoose post hooks
the post function will be executed after the defined hook
`typescript
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
@post("save")
private preSave(doc:Doc,next){
console.log('%s has been saved', doc._id);
next();
}
}
`Model
$3
register new schema model
`typescript
@model()
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
}
`
$3
inject model to class
`typescript
@define()
@singleton()
export class SomeManager { @injectModel(User) userModel:Model;
async getUser(id:string): Promise> {
let user = await this.userModel.findById(id)
return user;
}
}
`
Schema Api
$3
get the defined collection name on schema
`typescript
@model()
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
}User.collectionName // "user"
`
$3
return mongoose schema object
`typescript
@model()
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
}let schema = User.getSchema()
`$3
define and mongoose model instance by mongoose connection
`typescript
@model()
@schema("User",{strict:true})
export class User{
@prop({type:String})
name:string
}let model = User.getModel(mongoose.connection)
model.findById("someId")
`
ModelRepository
with modelRepository you can access to the mongoose connection and all the models$3
getter return mongoose connection$3
#### getModel(model: typeof Schema): Model
return mongoose model by schema type
`typescript
@define()
@singleton()
export class SomeManager { @inject() modelRepository:ModelRepository;
async getUser(id:string): Promise> {
let user = await this.modelRepository.getModel(User).findById(id)
return user;
}
}
``