忘掉Mongoose吧,這是更優雅的Mongorito

isNeilLin發表於2017-11-23

MongoDB安裝(mac)

# 進入 /usr/local
cd /usr/local

# 下載
sudo curl -O https://fastdl.mongodb.org/osx/mongodb-osx-x86_64-3.4.2.tgz

# 解壓
sudo tar -zxvf mongodb-osx-x86_64-3.4.2.tgz

# 重新命名為 mongodb 目錄
sudo mv mongodb-osx-x86_64-3.4.2 mongodb

# 把安裝目錄/bin新增到 PATH 路徑中
export PATH=/usr/local/mongodb/bin:$PATH

# 建立資料庫儲存目錄 /data/db
cd /
sudo mkdir data
cd /data
sudo mkdir db

# 啟動 mongodb,預設資料庫目錄即為 /data/db
sudo mongod
# 如果沒有建立全域性路徑 PATH,需要進入以下目錄
cd /usr/local/mongodb/bin
sudo ./mongod複製程式碼

Mongorito

MongoDB ORM for Node based on Redux

安裝

npm install mongorito --save
# or
yarn add mongorito複製程式碼

建立資料庫連線

const { Database } = require('mongorito');
const db = new Database('localhost/test');
async function do(){
    await db.connect();   
}複製程式碼

建立Model

//class “Model”沒有任何屬性和方法
const { Model } = require('mongorito'); 

class Post extends Model {}

// 在資料庫裡註冊 Model
db.register(Post);複製程式碼

建立Document

// 建立一個Model的例項
const post = new Post();
//or 
const post = new Post({
    title: 'First Post',
    author: {
        name: 'Neil Lin',
        age: 23
    },
    content: 'This is content',
    created: Date.now()
})複製程式碼

獲取document中的欄位

const title = post.get('title');
const author = post.get('author.name')複製程式碼

更新

async function do(){
    post.set('title','Second Post');
    post.set({
        author: {
            name: 'monica'
        },
        content: 'This content has already updated.'
    })

    await post.save()   
}複製程式碼

刪除

async function do(){
    // 刪除單個欄位
    post.unset('created');

    // 刪除多個欄位
    post.unset(['created','author.age'])

    await post.save();

    // 刪除document
    await post.remove();   
}複製程式碼

自增欄位

async function do(){
    const post = new Post({
        views: 0
    })

    await post.increment('views');

    post.get('views'); // => 1

    await post.increment('views', 2);

    post.get('views'); // => 3
}複製程式碼

一次增加多個欄位

async function do(){
    const post = new Post({
        views: 10,
        comments: 10
    })

    await post.increment({
        views: 5,
        comments: 2
    })

    post.get('views') // => 15
    post.get('comments') // => 12
}複製程式碼

巢狀其他Model

class Post extends Model {}
class Author extends Model {}
class Comments extends Model {}

Post.embeds('author', Author)
Post.embeds('comments', Comments)

const post = new Post({
    title: 'Great post',
    author: new Author({name: 'Steve'}),
    comments: [new Comment({body: 'Interesting!'})]
})
//or
const post = new Post({
    title: 'Great post',
    author: {
        name: 'Steve'
    },
    comments: [{
        body: 'Interesting!'
    }]
})

async function do(){
    await post.save();
}複製程式碼

查詢


async function do(){
    // 查詢全部posts
    await Post.find();

    // 查詢tag為"js"的posts
    await Post.find({tag: "js"});
    // or
    await Post.where({tag: "js"}).find();

    // 查詢最近5條posts
    await Post
            .limit(5)
            .sort('created','desc')
            .find();

    // 查詢其中一條
    await Post.findOne({title: 'First Post'});

    // 獲取posts條數
    await Post.count({author: 'Neil Lin'});
}複製程式碼

外掛

使用第三方外掛

const timestamp = require('mongorito-timestamps');

db.use(timestamp({
    createdAt: 'created', // default 'created_at'
    updatedAt: 'updated' // default 'updated_at'
}))
// 或者只用於某個Model
Post.use(timestamp({
    createdAt: 'created', // default 'created_at'
    updatedAt: 'updated' // default 'updated_at'
}))

async function do(){
    const post = new Post({title: 'Hello'});
    await post.save();
    post.get('created_at');
    //=> 2017-05-17T18:02:06.612Z
}複製程式碼

編寫外掛

const extendPost = Post => {
    Post.Recently = function() {
        return this
            .limit(5)
            .sort('created', 'desc')
            .find();
    }

    Post.prototype.setTag = function(tag) {
        this.set('tag',tag);
    }
}

Post.use(extendPost);

async function do(){
    const post = new Post();

    post.setTag('mongodb');

    await post.Recently(); //=> [Post, Post, Post]
}複製程式碼

相關文章