mongoose-model-ts is a package for Typescript node proyect to use mongoose in a type way.
Here is a basic example of how you can use the package:
Download this package using npm
npm i --save mongoose-model-ts
const mongoose = require('mongoose');
const { Schema } = mongoose;
const { ObjectId } = Schema.Types;
const { Editorial } = './editorial';
const { Enemy } = './enemy';
const HeroSchema = new Schema({
name: {
type: String
},
superpower: {
type: String,
required: true
},
editorial: {
type: ObjectId,
ref: 'Editorial'
},
enemies: [{
type: ObjectId,
ref: 'Enemy'
}],
})
mongoose.model('Hero', HeroSchema);
import { prop, Model, entity } from 'mongoose-model-ts'
import { Editorial } from './editorial';
import { Enemy } from './enemy';
@entity
export class Hero extends Model {
@prop()
name: string;
@prop({ required: true })
superpower: string;
@prop({ ref: Editorial })
editorial: Editorial;
@prop({ ref: Enemy })
enemies: Enemy[];
}
Mongoose TS map the properties of the model and create a schema in the metadata of the class. All is transparent for the developer and they don't need get worry about how its work.
const hero = await Hero.create({name: 'Batman', superpower: 'Be cool' });
const query = { /* ... */ };
const hero = await Hero.find(query);
const hero = await Hero.findByUd(/*id*/);
const hero = await Hero.findOne(query);
We can use Save for create or update if the record exist in the database.
// SAVE NEW RECORD
const hero = new Hero;
hero.name = 'Superman';
hero.superpower = 'Too much to be fair';
await hero.save();
// UPDATE OLD RECORD
const hero = await Hero.findByUd(/*id*/);
hero.superpower = 'new super amazing power';
hero.save();
The same as Save() function when the record exist.
// UPDATE OLD RECORD
const hero = await Hero.findByUd(/*id*/);
hero.name = 'Another craze and cool name';
hero.update();
The package allows you to access to a ref object directly without search, the package search and populate automaticly.
const hero = await Hero.findByUd(/*id*/);
// This automaticly find the editorial and save this into editorial property
const editorial = hero.editorial.name;
In this moment the package is un ultra mega archi prealpha. In the next weeks we will upload new cool features. Until that, we are hiring all types of recomendations to improve the package!
This project is licensed under the MIT License - see the LICENSE file for details
Generated using TypeDoc