npm-install camo

camo是針對Node.js和MongoDB的對象模型mapper(object document mapper)(ODM)javascript

能夠喝Mongoose ODM互換,可是和其有顯著的不一樣java

文章主要關注了Mongo ODMs新增的ES6特性,這些特性將不支持例如classes 和 schema 繼承等特性web

對於其餘語言學習者(例如java),基於類的ODMs他們更加熟悉,由於能夠很方便的聲明一個基本模塊,而後繼承此模塊。 Mongoose模型的繼承性比較差,因此camo中基於類的繼承是一個受歡迎的特性。mongodb

 

當我在使用Mongoose的時候,我嫉妒SQL使用者可使用SQLite來替代更大的相似MySQL或者PostgreSQL同樣的數據庫。 SQLite是一個輕量級的數據庫,用戶可使用一個簡單的文件做爲後端(backend),因此就木有必要下載和安裝300MB+(Mac OSX 壓縮版本)MySQL到你的電腦中來運行數據庫操做。數據庫

此外,MongoDB還有一個愈加流行的NeDB,這將存儲數據到一個單一的文件(或者內存中),且針對Node.js Mongo Driver有一個相同的API。npm

 

和Mongoose不一樣的是,Camo 支持 NeDB 做爲後端(backend),因此你不須要安裝全部的MongoDB數據庫,若是你不想安裝的話。這對開發和測試提供了很大便利,由於其減小了本地依賴(local dependencies) 且讓你的應用程序更加便攜——NeDB是一個你能夠從NPM簡單安裝的包。 因此只要你想要,你徹底能夠在建立產品初始階段使用NeDB做爲數據庫,以後再將其擴大成一個完整的Mongo 數據庫若是你的數據負載量增大。json

 

鏈接到數據庫後端

爲了支持不一樣的數據庫後端(database backends),camo經過一個URL字符串來了解從哪裏以及怎樣鏈接到你的數據庫。以下例:app

***javascript
var connect = require('camo').connect;

// Local Mongo database
connect('mongodb://localhost/camo_test').then(function(db) {
	// ...
});

// NeDB takes a directory path...
connect('nedb:///Users/scott/data/animals').then(function(db) {
	// ...
});

// ...or 'memory' for storing data in-memory
connect('nedb://memory').then(function(db) {
	// ...
});
```

一旦你鏈接到數據庫,你能夠開始建立而且保存你的模型(models)webapp

 

建立你本身的模型

建立一個模型,你要作的就是擴展(extend)文檔類型(the 'Document' class)而且具體化你的模式(schema)。給你能夠覆蓋的‘ static collectionName()’方法命名,且返回任何你想要的名稱;或者,若是你不想要指定一個特定的名字,camo將會使用c類名且增長一個s到名字的末尾讓其變成複數形式。

 

***javascript
var Document = require('camo').Document;

class User extends Document {
    constructor() {
        super();

        this.email = {
            type: String,
            unique: true
        };
        this.password = String;
        this.firstName = String;
        this.lastName = String;
        this.age = Number;
        this.created = {
            type: Date,
            default: Date.now
        };
        this.previousLogins = [Date];
    }

    static collectionName() {
        return 'users';
    }
}

 

上面咱們申明瞭‘User’對象,這個對象包含了典型的用戶數據,好比email,密碼和姓名。你可能主語到聲明schema的構造器使用了內置的JavaScript對象好比‘String’,'Number'和‘Date’。任何沒有使用下劃線做爲前綴來聲明的內容都包含在這個schema中。

 

在這些模型類中你可使用全部典型的類特性,好比getters/setters,靜態方法等等

***javascript
var Document = require('camo').Document;

class User extends Document {
    constructor() {
        super();

        // User schema here...
    }

    get fullName() {
        return this.firstName + ' ' + this.lastName;
    }

    canVote() {
        return this.age >= 18;
    }

    static getVoters() {
        return User.loadMany({ age: { $gte: 18 } });
    }
}

雖然ES6中的類語法只是一個糖衣語法(syntactic sugar),可是相對於舊的原型鏈方式,其更加便捷,易熟悉和易理解,特別是針對剛學JavaScript的用戶而言。

 

保存一個文檔

你若是想建立和保存一個新的用戶,那麼你須要使用'.create()'和'.save()'方法,以下

***javascript
var connect = require('camo').connect;

connect('mongodb://localhost/camo_test').then(function(db) {

    var user = User.create({
        email: 'billy@example.com',
        password: 'sekret',
        name: 'Billy Bob',
        age: 28,
        previousLogins: [Date.now()]
    });

    return user.save();
}).then(function(u) {
    console.log('Saved user Billy!');
});

如上,你剛剛建立且保存了一個用戶到MongoDB中

 

繼承

如今要講述Camo中最棒的部分啦。假設在你的webapp中,你有兩個不一樣類型的用戶類型——普通用戶和高級用戶。高級用戶相對於普通用戶有更多的特權和更多的相似支付信息等的數據。 爲了不只是爲了增長額外的支付信息而從新書寫'User' 模式(schema),咱們可使用繼承:

***javascript
class ProUser extends User {
    constructor() {
        super();

        this.cardNumber = String;
        this.cardExp = String;
        this.cardSecurityCode = String;
        this.lastPayment = Date;
    }
}

你可使用繼承屢次。繼承將繼承父類到子模式(schemas)中;若是父模式(schemas)或者其中的方法不知足你的設計,你能夠覆蓋它們。

 

內嵌數據

由於MongoDB數據不是寫死的,這也是咱們首先考慮使用它的緣由。因此,當你想要增長一些好比地址的內置數據時,該怎麼作?

你可以使用‘EmbeddedDocument’來聲明模式(shcema),並將其加入到已經存在的文檔類(document class)中間。這些內置的文檔不會被保存爲單獨的文檔,能夠被保存在其餘的模式(schemas)中:

***javascript
var EmbeddedDocument = require('camo').EmbeddedDocument;

// User class here...

class Address extends EmbeddedDocument {
    constructor() {
        super();

        this.addressLine1 = String;
        this.addressLine2 = String;
        this.city = String;
        this.state = String;
        this.zip = String;
    }
}

class ProUser extends User {
    constructor() {
        super();

        // Credit card details here...

        this.billingAddress = Address;
        this.shippingAddress = Address;
    }
}

這然呢能夠對待內置對象繼續昂對待其餘'Dpcument'對象同樣,因此你可給其設置getters/setters,實例方法和靜態方法。在全部的繼承和內置模式(nested schemas)添加了以後,咱們能夠建立一個最終的以下樂死的文檔

***json
{
    "email": "billy@example.com",
    "password": "a434287b3bfdd8de9f9f166f926dca10",
    "firstName": "Billy",
    "lastName": "Bob",
    "age": 28,
    "created": ISODate("2015-09-22T01:43:24.928Z"),
    "previousLogins": [ISODate("2015-11-16T03:53:46.678Z")],
    "cardNumber": "4242424242424242",
    "cardExp": "11/15",
    "cardSecurityCode": "123",
    "lastPayment": ISODate("2015-09-22T01:43:24.928Z"),
    "billingAddress": {
        "addressLine1": "123 Fake St.",
        "addressLine2": "",
        "city": "Cityville",
        "state": "NE",
        "zip": "12345"
    },
    "shippingAddress": {
        "addressLine1": "321 Code Circle",
        "addressLine2": "Suite 26",
        "city": "Villageville",
        "state": "NE",
        "zip": "54321"
    }
}

你得到了全部這些能夠從新再shcemas中從新利用的代碼,以後,你若是決定你的‘Address’內置數據須要包含‘Attn’這一行,你能夠增長它,且其會包含到任何使用‘Address’ ‘EmbeddedDocument’的地方。

 

加載和刪除文檔

如今,你若是想要備份數據,那麼可使用相似針對MongoDb JavaScript驅動器的loadOne()和loadMany()方法。

***javascript
User.loadOne({email: 'billy@example.com'}).then(function(user) {
    console.log('Found user:', user.id);
});

刪除文檔,你能夠在對象實例自己調用delete()方法,或者使用下面的靜態方法:

‘deleteOne(query, options)’ 

`deleteMany(query, options)`

`loadOneAndDelete(query, options)`

 

結束語:

能夠看更多的有關camo的內容(validation,hooks等等)

點擊查看例子   

原文連接:https://blog.xervo.io/npm-install-camo

相關文章
相關標籤/搜索