Sinaps Object Document Model
Sinaps ODM is a object document model for MongoDB-like databases.
Why not using Mongoose or Camo?
After a few month of building up frustrations with Mongoose, I tried Camo ODM. Camo is really a great step in the right direction but was missing a few key feature I needed. That's why Sinaps ODM was born.
Key features
- Built around ES6 Promise and Classes.
- Feature a strong Schema model that support nested Schema and array of Schema. All field in schema are typed, provide default value, custom getter and setter.
- All data are observed and can be listened for changes. Nested data change event bubble up to the root document.
- Provide built-in memory cache for reusing existing document.
- Trimed down, nothing-more-nothing-less than what you'd expect from an ODM.
Install
npm install --save sinaps-odm
Getting started
Initialize connection to database
Import Client from sinaps-odm
package and initialize new connection using Client.fromUri(uri)
. It returns a Promise and when it succeed, your ready to go.
var Client = require('sinaps-odm').Client;
Client.fromUri('mongodb://localhost:27017/test')
.then(client => {
})
.catch(err => {
console.error('Error', err.stack);
});
Create your first document
With the resulting client
, you can define new Document using client.document(collection, schema, options)
.
var User = client.document('user', {
name: String,
email: String
});
var john = new User({
name: 'John Doe',
email: 'john.doe@example.com'
});
john.save()
.then(() => {
console.log('John saved');
})
.catch(err => {
console.error('Could not save', err.stack);
})
Link two Document together
Let's say you have a Post document with a field author
that links to a User document.
var Post = client.document('post', {
title: String,
author: {
type: Client.ObjectId,
ref: 'user'
}
});
var postA = new Post({
title: 'Awesome new post by John',
author: '56aec5a51e4e6e1022d7e301'
});
console.log(postA.author.name);
Well that wasn't what we were expecting eh? That's because the process of populating the linked document is asynchronious.
var postA = new Post({
title: 'Awesome new post by John',
author: '56aec5a51e4e6e1022d7e301'
});
setTimeout(function () {
console.log(postA.author.name);
}, 1000);
Post.populate({
title: 'Awesome new post by John',
author: '56aec5a51e4e6e1022d7e301'
}).then(postB => {
console.log(postB.author.name);
});
var postC = new Post({title: 'Awesome new post by John'});
postC.populate({author: '56aec5a51e4e6e1022d7e301'}).then(postC => {
console.log(postC.author.name);
});
console.log(postC.author.name);