A mongoose Repository based Include Plugin:
- mongoose
- mongoose-delete (default options: { deletedAt: true, indexFields: true, overrideMethods: true })
- mongoose-history
- mongoose-paginate
- mongoose-timestamp
- mongoose-aggregate-paginate
npm install sendit-mongoose-repository --save
bar.repository.js file
import mongoose from 'mongoose'
import RepositoryBuilder from 'sendit-mongoose-repository'
const schemaDefinition = {
name: {
type: String,
require: true
},
foos: {
type: [Number],
require: true
},
company: { type: Mongoose.Schema.Types.ObjectId, ref: 'Company' },
}
export const builder = RepositoryBuilder('Bar', schemaDefinition)
export default builder.Repository
// builder provides:
// {
// Model,
// Schema,
// Repository,
// schemaDefinition
// }
.findOne(query: any, options: any)
.find(query: any = {}, options: any = {})
.create(data: any)
.update(query: any, data: any)
.upsert(query: any, data: any)
(default options: {upsert: true, new: true})
.delete(data: any)
.aggregate(data: any)
.aggregatePaginate(query: any, options)
Find one
import BarRepository from './bar.repository.js'
export default async function list() {
var filter = {
name: 'default'
}
var options = {
populate: 'company' //optional
}
return BarRepository.findOne(filter, options)
}
Find all
import BarRepository from './bar.repository.js'
export default async function list() {
var filter = {
name: 'default'
}
var options = {
populate: 'company' //optional
}
return BarRepository.find(filter, options)
}
Find with Paginate (required options.limit and options.page)
var filter = {
name: 'default'
}
var options = {
limit: 10, // required
page: 1, // required, start 1
sort: {name: -1}, // optional, default: {_id: 1}, (ex. sort descending name)
populate: 'company', // optional
select: '-_id -__v -password' // optional omit _id, __v, password
}
return BarRepository.find(filter, options)
Create
await BarRepository.create({ name: 'default' })
Update
await BarRepository.update({ name: 'default' }, { foos: [12, 69] })
Delete
await BarRepository.delete({ name: 'default' })
Aggregate
import BarRepository from './bar.repository.js'
export default async function list() {
var filter = {
name: 'default'
}
var options = {
populate: 'company' //optional
}
return BarRepository.find(filter, options)
}
Aggregate Paginate
var aggregateQuery = [
{ $match : { name: 'default' } },
{ $project: { foos: 1 } }
]
var options = {
limit: 10, // required
page: 1, // required, start 1
sort: {name: -1}
}
return BarRepository.aggregatePaginate(filter, options)