knex-odm
v1.6.0
Published
Mini-ODM with SQL backend based on Knex.js
Downloads
12
Readme
Knex.js-based ODM
Install
knex-odm requires knex
as peer dependency, so you need to install both:
npm i --save knex knex-odm
Create repositories
const knex = require('./knex');
const { repository, validators } = require('knex-odm');
const User = module.exports = repository(knex, {
table: 'user',
schema: {
'name': 'string', // type: 'string', required: true
'nickname': 'string?', // type: 'string', required: false
'role': {
type: 'string',
default: 'student',
validators: [
validators.enum('student', 'teacher', 'administrator'),
],
},
},
methods: {
await findByRole(role, limit = 25, offset = 0) {
return await this.query()
.where('role', role)
.orderBy('name', 'asc')
.limit(limit)
.offset(offset);
}
}
});
Use
async function main() {
const User = require('./repositories/user');
const teachers = await User.findByRole('teacher');
for (const teacher of teachers) {
console.log(teacher.name, teacher.role);
}
}