Specla database
This module is the database handler for the Specla Framework, its like Laravels
Eloquent but just for javascript and MongoDB.
Setup
To install specla-database all you have to do is to download it via npm.
npm install specla-database --save
let Database = require('specla-database');
const DB = new Database({
driver: 'mongo',
host: '127.0.0.1',
port: 27017,
database: 'MyDB'
});
Usage
Specla database includes two modules the Query builder
and the DB.Model
.
Query builder
Fetch data
DB.collection('users').get((err, result) => {
});
Stream data
DB.collection('users').stream((user) => {
return user;
}).done((result) => {
});
Validate against schema
let schema = {
name: String,
age: Number,
address: {
city: String,
},
skills: Array,
admin: Boolean,
};
let data = {
name: 'Frederik',
age: 22,
address: {
city: 'Odense',
},
skills: ['Javascript'],
admin: true
};
DB.collection('users')
.schema(schema)
.insert(data, (err, result) => {
});
Wheres
DB.collection('users')
.where('name', 'John')
.get((err, result) => {
});
It's also possible to just parse an object to the where()
like below
.where({ name: 'John' })
Sort
.sort('name', 'ASC')
Skip and limit
.skip(5)
.limit(10)
Insert
let data = {
name: 'John',
};
DB.collection('users')
.insert(data, (err, result) => {
});
Update
let data = {
name: 'John',
};
DB.collection('users')
.where('_id', '5748aa5d45af47fc9909310b')
.update(data, (err, result) => {
});
Remove
DB.collection('users')
.where('_id', '5748aa5d45af47fc9909310b')
.remove((err, result) => {
});
Raw
If there is some Mongo functionality which isn't supported yet in this module, you can then use the raw method and have full access to the Mongo object.
Its important to notice when youre using the raw method, you have to manually close the db connection with the done
callback
DB.raw((db, done) => {
var cursor = db.collection('users').find({});
cursor.each((err, doc) => {
if(doc !== null){
console.log(doc);
} else {
done();
}
});
})
Models
class User extends DB.Model {
collection(){
return 'users';
}
schema(){
return {
name: String,
age: Number
};
}
}
Create
let user = new User;
user.set('name', 'John');
user.save(() => {
console.log(user.get('_id'));
});
Find
User.find('5748aa5d45af47fc9909310b', (err, user) => {
});
Update
User.find('5748aa5d45af47fc9909310b', (err, user) => {
user.set('name', 'Frederik');
user.save(() => {
});
});
delete
User.find('5748aa5d45af47fc9909310b', (err, user) => {
user.delete(() => {
});
});
TODO
- Validation
- Mongo
- Advanced wheres
- Agregates
- Joins
- Model events
- Mysql(maybe later)